WPF DataGrid不更新只读值

时间:2019-04-03 09:37:10

标签: wpf datagrid

我有一个List<MyClass>,其中包含以下数据项:

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

以及以下数据绑定的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>

如果我更新myvalue列上的值,则myreadonly coolumn值不会更新,但是如果我创建一个调用以下按钮:

MyDataGrid.Items.Refresh();

myreadonly值已正确更新。

但是我想在myValue编辑操作(例如CellEditEnding)结束时更新值,并且在编辑过程中不能调用Refresh函数。我该怎么办?

谢谢。

1 个答案:

答案 0 :(得分:1)

只要将INotifyPropertyChanged设置为新值,就实施PropertyChanged并引发MyReadonlyValue属性的MyValue事件:

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));
    }
}
相关问题