我有两个文本框折扣(%)和价格(€)。 价格为只读。 DataGrid 中的行是通过名为 MyData 的类构建的,并且 Discount 绑定到值 discount , 价格至价格。当我更改折扣的percantage值时,它应该计算新价格并将源值 price 更改为新价格。但是它不会更新文本框 price 。我需要调用什么来触发目标更新?
Xaml:
<DataGridTemplateColumn Header="Discount(%)" Width="0.5*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Name="tbDiscount" Text="{Binding Path=discount, Mode=TwoWay}" TextChanged="tbDiscount_TextChanged"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Price (€)" Width="0.5*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Name="tbPrice" Text="{Binding Path=price, Mode=TwoWay}" IsReadOnly="True"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
C#:
我的数据:
public class MyData
{
public decimal price { set; get; }
public int discount { get; set; }
}
如何将行添加到 DataGrid
dataRow.discount = 0;
dataRow.price = price;
dataGridBasket.Items.Add(dataRow);
我如何尝试更改TextBox中的textvalueChanged的 price 值折扣:
private void tbDiscount_TextChanged(object sender, TextChangedEventArgs e)
{
var text = sender as TextBox;
text.GetBindingExpression(TextBox.TextProperty).UpdateSource();
foreach(MyData item in dataGridBasket.Items)
{
item.price = item.price - (item.price * (Convert.ToDecimal(item.discount) / 100));
}
}
答案 0 :(得分:1)
更改价格的逻辑应该在MyData
设置程序的discount
类中。在此处设置新的price
值,并在PropertyChangedEvent
设置器中提高price
。
您还需要将原始价格存储在某些字段/属性中,以正确计算折扣价。
public class MyData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private decimal _basePrice;
public decimal basePrice
{
get { return _basePrice; }
set { _basePrice = value; UpdatePrice(); }
}
private decimal _price;
public decimal price
{
get { return _price; }
}
private int _discount;
public int discount
{
get { return _discount; }
set { _discount = value; UpdatePrice(); }
}
private void UpdatePrice()
{
_price = _basePrice * (100 - _discount) * 0.01M;
OnPropertyChanged("price");
}
}
tbDiscount_TextChanged
变得多余,并且可以简化DataGrid列的定义:
<DataGridTemplateColumn Header="Discount(%)" Width="0.5*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=discount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Price (€)"
Width="0.5*"
Binding="{Binding Path=price}"
IsReadOnly="True" />