通过更改另一列来更改数据网格中一列的值

change value of one column in datagrid by changing another

我可以更改数据网格中数量列的值,但我似乎无法使用 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>

这是我的 c# WPF

private void DataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    AddItem row = (AddItem)dg.SelectedItems[0];
}

由此我可以轻松获得数量的新值,但似乎无法弄清楚如何更新同一行的 datagrid.itemsource 的总价格列。任何帮助将不胜感激

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 我缺少的东西

假设 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;
    }
}

这将告诉 UI 总价已更改,并将相应地更新网格。

另一种解决方案是扩展 AddItem class 以发送 PropertyChanged 事件。这将在使用 class 的任何地方发送事件,而不仅仅是在这个特定的视图模型上。

您的视图模型必须实现 INotifyPropertyChanged 才能正常工作。