我看到一些可用于行选择的选项,但“无选择”不是其中之一。我已经尝试通过将 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);
}
}
}
我在创建解决方案时使用了 this blog post。
关于wpf - 如何防止 WPF Toolkit DataGrid 中的行选择?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2765387/