如何防止在WPF Toolkit DataGrid中选择行? [英] How can I prevent row selection in the WPF Toolkit DataGrid?

查看:70
本文介绍了如何防止在WPF Toolkit DataGrid中选择行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些可用于行选择的选项,但是无选择不是其中之一。我尝试通过将SelectedItem设置为null来处理SelectionChanged事件,但该行似乎仍然处于选中状态。

I see a few options available for row selection, but 'No Selection' is not one of them. I've tried handling the SelectionChanged event by setting SelectedItem to null, but the row still seems selected.

如果没有防止这种情况的简便支持,这会很容易吗?只是将选定的行设置为与未选定的行相同的样式?这样就可以选择它,但是用户没有视觉指示器。

If there is no easy support for preventing this, would it be easy to just style the selected row the same as an unselected one? That way it could be selected, but the user has no visual indicator.

推荐答案

您必须调用BeginGrid异步调用DataGrid.UnselectAll。使它工作。我编写了以下附加属性来处理此问题:

You have to call DataGrid.UnselectAll asynchronously with BeginInvoke to get it to work. I wrote the following attached property to handle this:

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 sourced this blog post in creating my solution.

这篇关于如何防止在WPF Toolkit DataGrid中选择行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆