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

4

我看到有几种可用于行选择的选项,但是“无选择”不在其中。 我尝试通过将 SelectedItem 设置为 null 处理 SelectionChanged 事件,但是该行仍然似乎被选中。

如果没有轻松的支持来防止这种情况,那么将选中的行样式与未选中的行相同是否容易? 这样它就可以被选择,但用户没有视觉指示。


你想将它设为只读吗? - Archie
它已经是只读的了。我可以通过单元格上的属性轻松地实现这一点。我只是不想允许行选择。我开始认为将选定的行样式与未选定的行相同可能是答案。 - Kilhoffer
3个回答

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);
        }
    }
}

我在创建解决方案时参考了这篇博客文章

这是一个奇怪问题的绝妙解决方案。如果我可以给你点赞超过一次,我一定会的!完美解决了问题。 - Kilhoffer

1
请将以下样式应用于datagid单元格以解决问题:
<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>

0

可以使用属性“IsHitTestVisible”将任何行选择设置为False。但是这样做将不允许您使用数据网格的滚动条。在这种情况下,数据网格将被锁定。 另一种解决方案是: 您可以对数据网格的单元格应用样式。这对我有用。请使用以下代码:

<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
</Style>

以上代码对我有效。希望对您也有用。

敬礼, Vaishali


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接