Search code examples
wpfdatagrid

WPF DataGrid not updating read only values


I have a List<MyClass> with the following data item:

class MyClass
{
    public double MyValue { get; set; } = 0;
    public double MyReadonlyValue
    {
        get { return MyValue +1; }
    }
}

And the following databound DataGrid:

<DataGrid ItemsSource="{Binding MyList}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=MyValue}" Header="myvalue"/>
        <DataGridTextColumn Binding="{Binding Path=MyReadonlyValue}" Header="myreadonlyvalue" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

If I update the values on myvalue column the myreadonly column values does not update, but if I create a button that calls:

MyDataGrid.Items.Refresh();

the myreadonly value gets updated correctly.

But I'd like to the values being updated at the end of the myValue edit operation (like CellEditEnding) and during edit I can't call Refresh function. How could I do?

Thanks.


Solution

  • Implement INotifyPropertyChanged and raise the PropertyChanged event for the MyReadonlyValue property whenever MyValue is set to a new value:

    class MyClass : INotifyPropertyChanged
    {
        private double _myValue;
        public double MyValue
        {
            get { return _myValue; }
            set
            {
                _myValue = value;
                NotifyPropertyChanged();
                NotifyPropertyChanged(nameof(MyReadonlyValue));
            }
        }
    
        public double MyReadonlyValue
        {
            get { return MyValue + 1; }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }