如何刷新"一些其他文本列的值更改(WPF)时DataGrid TextColumn值?

时间:2017-03-16 13:31:30

标签: c# wpf data-binding datagrid inotifypropertychanged

我对WPF很陌生,所以当其他一些列更改其值时,我有点在刷新数据网格中某些列的值。

XAML:

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" CanUserSortColumns="True" CanUserAddRows="False" CanUserReorderColumns="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Index" Binding="{Binding Path=Index}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding Path=Description}" Header="Description" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding Path=Price}" Header="Price" Width="Auto" IsReadOnly="True"/>
<DataGridTextColumn x:Name="quantityBox" Binding="{Binding Path=Quantity, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Quantity"/>
<DataGridTextColumn Binding="{Binding Path=Discount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="False" Header="Discount(%)"/>
<DataGridTextColumn Binding="{Binding Path=TotalPrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Total" IsReadOnly="True" Width="Auto"/>
</DataGrid.Columns>
</DataGrid>

这是我使用的课程:

public class MyClass
{
    public int Index { get; set; }
    public string Description { get; set; }
    public double Price { get; set; }
    public int Quantity { get; set; }
    public double Discount { get; set; }
    public double TotalPrice { get; set; }
}

我为我的dataGrid设置了List作为ItemsSource:

List<MyClass> items = GetFromDB();
dataGrid.ItemsSource = items;
dataGrid.Items.Refresh();

现在,我想要做的是更新/刷新&#34; TotalPrice&#34;一旦用户改变&#34;折扣&#34;或&#34;数量&#34;列并反映在dataGrid中立即更改。

在这里查看Stackoverflow和MSDN文档中的现有问题后,我可以通过INotifyPropertyChanged事件来完成,但我实际上并没有完全了解。

有人可以详细说明这是如何完成的,还是指出一些解决相同/类似问题的详细教程?

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须在ViewModel MyClass中实现INotifyPropertyChanged。 更改“折扣”或“数量”属性时,应计算TotalPrice,并且在实施INotifyPropertyChange后,视图将识别更改和更新。当您未实现此界面时,View将在ViewModel更改时不会收到通知。

MyClass应该看起来像这样(只为一个属性做了例子)

public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    double totalPrice;
    public double TotalPrice
    {
        get
        {
            return totalPrice;
        }

        set
        {
            totalPrice = value;
            OnPropertyChanged("TotalPrice");
        }
    }
}