簡體   English   中英

WPF DataGrid禁用的單元正在接收文本輸入

[英]WPF DataGrid disabled cell is receiving text input

考慮以下具有三列的DataGrid:

在此處輸入圖片說明

只要年齡為-1,相應的單元就會被禁用。

理想情況下,用戶不得更改禁用的單元格值。 但是,請考慮用戶在第1行中,並且鍵盤焦點位於“年齡”列的相應單元格中,然后按Enter,現在用戶鍵入任何數字,而禁用的單元格將獲得該值! 這是期望的行為嗎? 我如何避免這種行為?

在此處輸入圖片說明

復制問題:

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

我不確定為什么會發生這種情況,但是您可以捕獲Enter事件並取消Edit:

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">

我得到了解決方案(添加了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());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM