我最近遇到了类似的问题。我需要在一个人创建一行并填充数据后,即创建一个新的Person后,将DataGrid中带有Id的单元格设置为只读。我尝试使用此解决方案:https://stackoverflow.com/a/43006150,但它在最初加载的行中有一个只读单元格,但在我添加和编辑的行中没有。 预先感谢您的合作。
班级人物:
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public Person(int id, string firstName, string secondName)
{
Id = id;
FirstName = firstName;
SecondName = secondName;
}
public Person()
{
Id = 0;
FirstName = "";
SecondName = "";
}
}
MainWindow.xaml:
<Window x:Class="NameDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:NameDataGrid"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" BeginningEdit="PersonDataGrid_BeginningEdit" IsReadOnly="false">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Header="Id" Binding="{Binding Path=Id}"/>
<DataGridTextColumn Width="*" Header="FirstName" Binding="{Binding Path=FirstName}"/>
<DataGridTextColumn Width="*" Header="SecondName" Binding="{Binding Path=SecondName}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
ObservableCollection<Person> persons;
public MainWindow()
{
InitializeComponent();
persons = new ObservableCollection<Person>() {
new Person(1, "erh", "erh"),
new Person(2, "erh", "reh"),
new Person(3, "erh", "erh"),
};
PersonDataGrid.ItemsSource = persons;
}
private void PersonDataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
if ((string)e.Column.Header == "Id")
{
if (!e.Row.IsNewItem)
{
e.Cancel = true;
}
}
}
}
因此,我决定检查该行中的值是否为默认值
private void PersonDataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
if ((string)e.Column.Header == "Id")
{
Person Person = e.Row.Item as Person;
if (!e.Row.IsNewItem || !(Person.Id == 0))
{
e.Cancel = true;
}
InitializeComponent();
}
}