我有一个DataGrid来输入销售屏幕的商品/价格/数量,我需要一个subTotal列,Price * Quantity,我不知道当用户离开Price时如何计算subTotal列或数量列。这是我的xaml
<DataGrid ItemsSource="{Binding Path=Datos,Mode=TwoWay,NotifyOnSourceUpdated=True}"
SelectedItem="{Binding Dato,Mode=TwoWay,NotifyOnSourceUpdated=True}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{ Binding Path=Descripcion}"></DataGridTextColumn>
<DataGridTextColumn Header="Price" Binding="{ Binding Path=Precio,UpdateSourceTrigger=PropertyChanged}" ></DataGridTextColumn>
<DataGridTextColumn Header="Quantity" Binding="{ Binding Path=Cant,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn>
<DataGridTextColumn Header="Total" Binding="{ Binding Path=Total,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
我的ViewModel是这样的:
public class VM : VMBase
{
public VM()
{
Datos.Add(new CDato() { Descripcion = "item 1", Precio = 2.5m, Cant = 3m, Total = 7.5m });
Datos.Add(new CDato() { Descripcion = "item 2", Precio = 5m, Cant = 2m, Total = 10m });
}
private ObservableCollection<CDato> _datos;
public ObservableCollection<CDato> Datos
{
get
{
if (_datos == null)
_datos = new ObservableCollection<CDato>();
return _datos;
}
set
{
_datos = value;
RaisePropertyChanged();
}
}
public void Calcular()
{
if (Dato != null)
{
Dato.Total = Dato.Precio * Dato.Cant;
RaisePropertyChanged("Dato");
RaisePropertyChanged("Datos");
}
}
private CDato dato;
public CDato Dato
{
get { return dato; }
set
{
dato = value;
RaisePropertyChanged();
}
}
}
public class CDato
{
public string Descripcion { get; set; }
public decimal Precio { get; set; }
public decimal Cant { get; set; }
public decimal Total { get; set; }
}
当用户更改单元格时,#14; Precio&#34; (价格)或&#34; Cant&#34; (数量)&#34; Total&#34;必须使用此公式计算列Tota = Precio * Cant
我无法找到相关的样本。
你能帮我解决这个问题吗?
很多人
答案 0 :(得分:3)
您可以通过向道具添加RaisePropertyChanged( "Total" )
来创建此内容,用于计算Total
属性。我已经创建了一些例子来解释如何。
<DataGrid ItemsSource="{Binding Objects}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding Price, UpdateSourceTrigger=PropertyChanged}" />
<DataGridTextColumn Width="100" Binding="{Binding Total}" />
</DataGrid.Columns>
</DataGrid>
viewModel道具。
private int _price;
public int Price
{
get { return _price; }
set { _price = value; RaisePropertyChanged( "Price" ); RaisePropertyChanged( "Total" ); }
}
public int Total
{
get { return _price * 2; }
}
<强>更新强>
根据评论。有必要为NotifyPropertyChanged
类实施CDato
(或从VMBase
派生)并为其添加RaisePropertyChanged
道具。