所以我有以下代码用于审核我们的库存。在编辑DataGrid上的actual_quantity
单元格后,ItemAuditInstance
实例会自动更新,设置其actual_quantity
并计算其difference
。我的问题是DataGrid自动刷新actual_quantity
但不是difference
我知道您可以通过将DataGrid的ItemsSource设置为null然后返回列表来强制刷新,但这似乎是浪费资源,因为我不想只为一个刷新数百行值。有没有办法做到这一点?
ItemAuditInstance:
public class ItemAuditInstance : ReflectionObject {
public int id { get; set; }
public int bfk_item_audit_id { get; set; }
public string item { get; set; }
public int current_quantity { get; set; }
public int actual_quantity { get; set; }
public int difference { get; set; }
public int ds_actual_quantity {
get {
return actual_quantity;
}
set {
actual_quantity = value;
difference = current_quantity - actual_quantity;
}
}
XAML:
<DataGrid x:Name="dgItems" Margin="0,0,0,50" AutoGenerateColumns="False" HorizontalContentAlignment="Right" RowEditEnding="dgItems_RowEditEnding">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding item}" Header="Item" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding current_quantity}" Header="Current Quantity" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding ds_actual_quantity, UpdateSourceTrigger=PropertyChanged}" Header="Actual Quantity" IsReadOnly="False"/>
<DataGridTextColumn Binding="{Binding difference}" Header="Difference" IsReadOnly="True" Width="*"/>
</DataGrid.Columns>
</DataGrid>
答案 0 :(得分:2)
您应该在ItemAuditInstance类中实现INotifyPropertyChanged,并在单元格绑定中将UpdateSourceTrigger设置为PropertyChanged(就像您在ds_actual_quantity的绑定中一样),以实现此类行为。 在您的示例中,实际数量的绑定设置正确,但是如果没有INotifyPropertyChanged,它有时可能无法正常工作。 我建议使用支持私有字段来允许静默更改(有时需要避免无限循环)
您对INotifyPropertyChanged的实现应如下所示:
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
private int _difference;
public int Difference
{
get
{
return _difference;
}
set
{
_difference = value;
OnPropertyChanged(new PropertyChangedEventArgs("Difference"));
}
}
与XAML一起:
<DataGridTextColumn Binding="{Binding Difference, UpdateSourceTrigger=PropertyChanged}" Header="Difference" IsReadOnly="True" Width="*"/>
现在刚刚开始 差异= current_quantity - actual_quantity 并且应该自动更新绑定