我可以更改数据网格中的quanity列的值,但我似乎无法使用celleditending事件更新同一行的总价格列这是我的xaml
<DataGrid AutoGenerateColumns="False" EnableColumnVirtualization="False" EnableRowVirtualization="False" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding SelectedItem}" Grid.Row="3" Grid.ColumnSpan="2" Name="DataGrid1" ItemsSource="{Binding DataGridItemsSource, Mode=TwoWay, IsAsync=True}" Margin="10,10,10,10" PreviewKeyDown="DataGrid1_PreviewKeyDown" SelectionChanged="DataGrid1_SelectionChanged" CellEditEnding="DataGrid1_CellEditEnding" BeginningEdit="DataGrid1_BeginningEdit" >
<DataGrid.Columns>
<DataGridTextColumn Header="Item Name" IsReadOnly="True" Binding="{Binding Path=ItemName}" Width="*"></DataGridTextColumn>
<DataGridTextColumn Header="Item Price" IsReadOnly="True" Binding="{Binding Path=ItemPrice}" Width="*"></DataGridTextColumn>
<DataGridTextColumn x:Name="QuantityColumn" Header="Quantity" IsReadOnly="False" Binding="{Binding Path=Quantity, Mode=TwoWay}" Width="*"></DataGridTextColumn>
<DataGridTextColumn Header="Total Price" IsReadOnly="True" Binding="{Binding Path=TotalPrice, Mode=TwoWay}" Width="*"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
这是我的#WPF for
private void DataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
DataGrid dg = sender as DataGrid;
AddItem row = (AddItem)dg.SelectedItems[0];
}
从这里我可以轻松获得数量的新值,但似乎无法弄清楚如何更新同一行的datagrid.itemsource的totalprice列。任何帮助将不胜感激
public class AddItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string ItemName { get; set; }
public float ItemPrice { get; set; }
public string Price { get; set; }
public int Quantity { get; set; }
public decimal TotalPrice { get; set; }
public int Size
{
get { return Quantity; }
set
{
Quantity = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Size"));
}
}
}
这是Additem我缺少的东西
答案 0 :(得分:1)
假设TotalPrice = Quantity * ItemPrice
,并且已经是AddItem
的计算属性,则需要为每个项添加PropertyChanged
处理程序:
foreach (var item in DataGridItemsSource)
{
item.PropertyChanged += item_PropertyChanged;
}
并添加处理程序:
private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Quantity":
case "ItemPrice":
PropertyChanged(this, "TotalPrice");
break;
}
}
这将告诉用户界面总价格已经改变,并将相应地更新网格。
另一种解决方案是扩展AddItem
类以发送PropertyChanged事件。这会将事件发送到使用类的任何地方,而不仅仅是在这个特定的视图模型上。
您的视图模型必须实现INotifyPropertyChanged
才能实现此目的。