考虑以下具有三列的 DataGrid:
当年龄为 -1 时,相应的单元格将被禁用。
理想情况下,用户不能更改禁用的单元格值。但是考虑到用户在第 1 行,键盘焦点在 Age 列的相应单元格中,然后按 Enter,现在用户键入任意数字,禁用的单元格获取该值!这是理想的行为吗?我怎样才能避免这种行为?
要复制问题:
- 选择 Age 列第 1 行中的单元格
- 按回车
- 输入一个数字
可重现的代码:
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; }
}
}
}