通过数据绑定更新数据网格"Total Quantity"单元格



我正试图让数据网格自动将";累积的";当构成该累计数量的列发生更改时,计数列。

当我更改列中的值时,TotalQuantity值在数据网格列中永远不会更新。我在同一视图中放置了一个相同的数据网格,以确保数据绑定正常工作——事实确实如此。如果我在顶部数据网格中进行了更改,它将反映在较低的网格中。

我的型号:

public class HardwareEditorModel
{
public string Description { get; set; }
public int Type { get; set; }
public int ModelQuantity { get; set; }
public int ManualQuantity { get; set; }
public int AutoExtra { get; set; }
public int TotalQuantity
{
get { return ModelQuantity + ManualQuantity + AutoExtra; }
}
}

ViewModel:

public class HardwareEditorViewModel : ObservableObject
{
private ObservableCollection<HardwareEditorModel> _hardwareEditorModels;
public ObservableCollection<HardwareEditorModel> HardwareEditorModels
{
get => _hardwareEditorModels;
set => SetProperty(ref _hardwareEditorModels, value);
}
public HardwareEditorViewModel()
{
HardwareEditorModels = new ObservableCollection<HardwareEditorModel>
{
new HardwareEditorModel { Description = "NUT", Type = 1, ModelQuantity = 10, ManualQuantity = 0, AutoExtra = 5 },
new HardwareEditorModel { Description = "BOLT", Type = 0, ModelQuantity = 100, ManualQuantity = 10, AutoExtra = 5 }
};
}
}

和视图:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding HardwareEditorModels, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="200">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{Binding Description}" />
<DataGridTextColumn Header="Type" Binding="{Binding Type}" />
<DataGridTextColumn Header="Model Quantity" Binding="{Binding ModelQuantity}" />
<DataGridTextColumn Header="Manual Quantity" Binding="{Binding ManualQuantity}" />
<DataGridTextColumn Header="Auto Extra" Binding="{Binding AutoExtra}" />
<DataGridTextColumn Header="Total" Binding="{Binding TotalQuantity, Mode=OneWay}" />
</DataGrid.Columns>
</DataGrid>

您需要让HardwareEditorModel也实现INotifyPropertyChanged,并在用于计算TotalQuantity的基础属性之一(ModelQuantityManualQuantityAutoExtra(发生更改时为其引发PropertyChanged事件。

例如,对ObservableObject类进行一些假设:

public class HardwareEditorModel : ObservableObject
{
private int _modelQuantity;        
public int ModelQuantity 
{ 
get => _modelQuantity;
set 
{
if (!SetProperty(ref _modelQuantity, value)) return;
RaisePropertyChanged(nameof(TotalQuantity));
}
}
// ....
}

相关内容

  • 没有找到相关文章