如何防止WPF Toolkit DataGrid中的行选择?

Kil*_*fer 4 wpf wpftoolkit wpfdatagrid

我看到一些选项可用于行选择,但"No Selection"不是其中之一.我已经尝试通过将SelectedItem设置为null来处理SelectionChanged事件,但似乎仍然选中了该行.

如果没有简单的支持来防止这种情况,那么将所选行的样式设置为与未选择的行相同是否容易?这样就可以选择它,但是用户没有可视指示符.

Jos*_*ant 5

您必须与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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在创建我的解决方案时获得了这篇博客文章.