c# - 绑定受其他属性影响的 DataContext 值
问题描述
我为数据上下文创建了一个类
public class Amt
{
private double _Amount = 0;
public double Amount
{
get { return _Amount; }
set { _Amount = value; }
}
private double _RedeemAmount = 0;
public double RedeemAmount
{
get { return _RedeemAmount; }
set
{
_RedeemAmount = value;
}
}
private double _BalAmount = 0;
public double BalAmount
{
get { return Amount - RedeemAmount; }
}
}
我已经将它绑定到 XAML 的 TextBox
<TextBox Name="txtAmount" Text="{Binding Amount}" FontSize="16" Margin="0,0,0,2"/>
<TextBox Name="txtRedeemAmount" Text="{Binding RedeemAmount,Mode=TwoWay}" FontSize="16" Margin="0,0,0,2" TextChanged="TxtRedeemAmount_TextChanged"/>
<TextBox Name="txtBalAmount" Text="{Binding BalAmount}" FontSize="16" Margin="0,0,0,2"/>
然后,我想要的是当我在 TextChanged 事件中更改兑换金额时,我希望余额金额也应该改变,我做了一些研究并尝试了一些代码,但它只是不起作用。我做错了吗?还有其他方法可以更好地做到这一点吗?
private void TxtRedeemAmount_TextChanged(object sender, EventArgs e)
{
double amt = 0;
double.TryParse(txtRedeemAmount.Text, out amt);
Amt.RedeemAmount = amt;
}
无论如何感谢您的帮助!
解决方案
要完成您想要的,您需要实现 INotifyPropertyChanged 接口。每当更改类的属性时,您都应该触发 PropertyChanged 事件。
using System.ComponentModel;
public class Amt : INotifyPropertyChanged
{
private double _Amount = 0;
public double Amount
{
get { return _Amount; }
set
{
_Amount = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Amount)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BalAmount)));
}
}
private double _RedeemAmount = 0;
public double RedeemAmount
{
get { return _RedeemAmount; }
set
{
_RedeemAmount = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RedeemAmount)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BalAmount)));
}
}
private double _BalAmount = 0;
public double BalAmount
{
get { return Amount - RedeemAmount; }
}
public event PropertyChangedEventHandler PropertyChanged;
}
推荐阅读
- android - 使用广播接收器以编程方式检查开发人员选项
- java - 如何在 optional.orElseThrow(..) 中抛出异常之前执行操作
- angular - mat-autocomplete 在 mat-table 内不起作用
- postgresql - 无法将 Ldap 添加到 PGAdmin
- jquery - JQuery Ajax UrlAction 更改页面 URL MVC
- json - 将json数据保存在flutter的收藏列表中
- go - 通道和优雅关闭死锁
- python - 从课堂上获取字典?
- r - 如何使用嵌套列表存储多个 for 循环?
- javascript - 为什么while循环内的函数不起作用?