我看到有几种可用于行选择的选项,但是“无选择”不在其中。 我尝试通过将 SelectedItem 设置为 null 处理 SelectionChanged 事件,但是该行仍然似乎被选中。
如果没有轻松的支持来防止这种情况,那么将选中的行样式与未选中的行相同是否容易? 这样它就可以被选择,但用户没有视觉指示。
我看到有几种可用于行选择的选项,但是“无选择”不在其中。 我尝试通过将 SelectedItem 设置为 null 处理 SelectionChanged 事件,但是该行仍然似乎被选中。
如果没有轻松的支持来防止这种情况,那么将选中的行样式与未选中的行相同是否容易? 这样它就可以被选择,但用户没有视觉指示。
您需要使用BeginInvoke异步调用DataGrid.UnselectAll方法才能使其起作用。我编写了以下的附加属性来处理这个问题:
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);
}
}
}
<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>
可以使用属性“IsHitTestVisible”将任何行选择设置为False。但是这样做将不允许您使用数据网格的滚动条。在这种情况下,数据网格将被锁定。 另一种解决方案是: 您可以对数据网格的单元格应用样式。这对我有用。请使用以下代码:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Style>
以上代码对我有效。希望对您也有用。
敬礼, Vaishali