How can I prevent row selection in a DataGrid Toolkit WPF?

I see several row selection options, but "No Selection" is not one of them. I tried to handle the SelectionChanged event by setting SelectedItem to null, but the row still seems to be selected.

If there is no easy support to prevent this, is it easy to just select the selected row as well as the unselected? Thus, it can be selected, but the user does not have a visual indicator.

+4
source share
3 answers

You must call DataGrid.UnselectAll asynchronously with BeginInvoke to make it work. For this, I wrote the following attached property:

using System; using System.Windows; using System.Windows.Threading; using Microsoft.Windows.Controls; namespace DataGridNoSelect { public static class DataGridAttach { public static readonly DependencyProperty IsSelectionEnabledProperty = DependencyProperty.RegisterAttached( "IsSelectionEnabled", typeof(bool), typeof(DataGridAttach), new FrameworkPropertyMetadata(true, IsSelectionEnabledChanged)); private static void IsSelectionEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var grid = (DataGrid) sender; if ((bool) e.NewValue) grid.SelectionChanged -= GridSelectionChanged; else grid.SelectionChanged += GridSelectionChanged; } static void GridSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var grid = (DataGrid) sender; grid.Dispatcher.BeginInvoke( new Action(() => { grid.SelectionChanged -= GridSelectionChanged; grid.UnselectAll(); grid.SelectionChanged += GridSelectionChanged; }), DispatcherPriority.Normal, null); } public static void SetIsSelectionEnabled(DataGrid element, bool value) { element.SetValue(IsSelectionEnabledProperty, value); } public static bool GetIsSelectionEnabled(DataGrid element) { return (bool)element.GetValue(IsSelectionEnabledProperty); } } } 

I created this blog post in creating my solution.

+5
source

Please apply below style to datagid cell to solve the problem:

 <Style x:Key="MyDatagridCellStyle" TargetType="{x:Type Custom:DataGridCell}"> <Setter Property="Focusable" Value="false"/> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="#434342"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="FontFamily" Value="Arial"/> <Setter Property="FontSize" Value="11"/> <Setter Property="FontWeight" Value="Normal"/> </Style> 
+1
source

Any row selection can be avoided by using the IsHitTestVisible property as False. But this will not allow you to use the scrollbar of your datagrid. In this case, the Datagrid will be blocked. Another solution: You can apply the style to the datagrid cell. It worked for me. Use the code as shown below:
Worked on the code for me. Hope this works for you too.

Regards, Vaishali

0
source

Source: https://habr.com/ru/post/1308769/


All Articles