A cell in a DataGrid becomes ReadOnly only after creating a row and filling it with data for the first time

  Kiến thức lập trình

I recently encountered a similar problem. I need to make the cell with Id in the DataGrid read-only after a person creates a row and fills in the data, that is, creates a new Person. I tried to use this solution: /a/43006150, but it has a ReadOnly cell in the initially loaded rows, but not in those that I add and edit.
Thank you in advance for your cooperation.

Class Person:

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


LEAVE A COMMENT