我看到一些可用于行选择的选项,但“无选择”不在其中。我尝试通过将SelectedItem设置为null来处理SelectionChanged事件,但该行似乎仍处于选中状态。
如果没有简单的支持来防止这种情况,那么只将选定行的样式设置为与未选定行相同的样式是否容易?这样就可以选择它,但用户没有可视指示器。
发布于 2010-05-05 00:53:19
您必须使用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。
https://stackoverflow.com/questions/2765387
复制相似问题