WPF数据网格禁用的单元格仍然可以输入文本

3
考虑下面拥有三列的DataGrid:

enter image description here

当年龄为-1时,相应的单元格将被禁用。

理想情况下,用户不应该能够更改禁用单元格的值。但是考虑到用户在第1行并且键盘焦点位于年龄列的相应单元格中,并按Enter键,现在用户输入任何数字,禁用单元格将获取该值!这是期望的行为吗?如何避免这种行为?

enter image description here

复制问题:

  1. 选择年龄列第1行的单元格
  2. 按回车键
  3. 输入一个数字

可重现的代码:

XAML:

<Window x:Class="wpf_behaviour.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridDetailsSample" Height="200" Width="400">
    <Grid Margin="10">
        <DataGrid Name="dgUsers" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="Age" Binding="{Binding Age}">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Age}" Value="-1">
                                    <Setter Property="IsEnabled" Value="False"/>
                                    <Setter Property="ToolTip" Value="This filed is diabled."/>
                                    <Setter Property="Background" Value="LightGray"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

相应的cs:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;

namespace wpf_behaviour
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<User> users = new List<User>();
            users.Add(new User() { Id = 1, Name = "Kumar", Age = 10 });
            users.Add(new User() { Id = 2, Name = "Sameer", Age = -1 });
            users.Add(new User() { Id = 3, Name = "Danny", Age= 16 });

            dgUsers.ItemsSource = users;
        }

        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
}

请查看此帖子 https://dev59.com/oZffa4cB1Zd3GeqP-qTv - Salah Akbari
@S.Akbari 设置 <Setter Property="FrameworkElement.IsHitTestVisible" Value="False"/> 没有起到作用! - Abbas
2个回答

0
我不确定为什么会发生这种情况,但您可以捕获“Enter”事件并取消编辑:

C#

private void MyDataGrid_OnKeyDown(object sender, KeyEventArgs e)
{
    var dg = sender as DataGrid;

    // alter this condition for whatever valid keys you want - avoid arrows/tab, etc.
    if (dg != null && !dg.IsReadOnly && e.Key == Key.Enter)
    {
        dg.CancelEdit();
        e.Handled = true;
    }
}

XAML

<DataGrid Grid.Column="1" Name="dgUsers" AutoGenerateColumns="False" PreviewKeyDown="MyDataGrid_OnKeyDown">

我不想取消所有的 Key.Enter。而且,接收值的禁用单元格的任何事件都没有被触发。所以,我绝对没有办法找出接收文本的单元格是否为禁用单元格。 - Abbas

0
我已经找到了解决方案(添加了 PreviewKeyDown 事件处理程序),以下是代码,如果有更好的解决方案,请告诉我:
private void DataGridCell_PreviewKeyDown(object sender, KeyEventArgs e)
{
    try
    {
        DataGridCell cl = (DataGridCell)sender;
        //Get the Cell's parent row
        //using System.Windows.Media; for VisaualTreeHelper 
        var DataGridRowParent = VisualTreeHelper.GetParent(cl);
        while (DataGridRowParent != null && DataGridRowParent.GetType() != typeof(DataGridRow))
        {
            DataGridRowParent = VisualTreeHelper.GetParent(DataGridRowParent);
        }
        //Get the Row's parent DataGrid
        var DataGridParent = VisualTreeHelper.GetParent(DataGridRowParent);
        while (DataGridParent != null && DataGridParent.GetType() != typeof(DataGrid))
        {
            DataGridParent = VisualTreeHelper.GetParent(DataGridParent);
        }

        DataGrid dp = DataGridParent as DataGrid;
        //Get the CurrentCell value of DataGrid
        DataGridCellInfo cli = dp.CurrentCell;

        var CellContent = cli.Column.GetCellContent(cli.Item);
        if (CellContent != null)
        {
            //Get DataGridCell of DataGridCellInfo
            DataGridCell dgc = (DataGridCell)CellContent.Parent;
            if (dgc.IsEnabled == false)
            {
                //If the key pressed is Enter or Tab allow
                if (e.Key == Key.Enter || e.Key == Key.Tab)
                {
                    e.Handled = false;
                    return;
                }
                //If any other key is pressed don't allow.
                e.Handled = true;
                return;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

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