我的 wpf 应用程序中有以下绑定(bind)
xaml:
<TextBox Text="{Binding Amount, StringFormat=c}" Name="txtAmount" />
c#(代码隐藏):
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
// needed to create the binding
this.DataContext = this;
}
private decimal _Amount;
public decimal Amount
{
get {
return _Amount;
}
set{
_Amount= value;
OnPropertyChanged("Amount");
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
//.....
该代码工作正常。每当我更改 txtAmount 的值时,我后面的代码中的属性 Amount 都会更新,反之亦然(在 C# 中更改 Amount 的值将更新 txtAmount)
无论如何,每次更改控件 txtAmount 中的文本时如何更新金额?我不想等到 txtAmount 失去焦点,以便在后面的代码中更新 Amount。
我尝试过的事情:
txtAmount.TextChanged += (a, b) =>
{
Amount = decimal.Parse(txtAmount.Text);
};
回想一下,我的 txtAmount 被格式化为货币,因此如果它的值为 1,那么 txtAmount 将显示 $1.00 我知道我应该能够将 $ 替换为空,以便能够将其转换为十进制。如果此应用程序使用不同的文化,例如 es 表示西类牙语,那么文本框将显示 eruo 而不是 $,我将不得不替换该符号以便能够转换它。
简而言之,有没有一种方法能够在每次该控件中的文本更改时而不是在控件失去焦点时更新绑定(bind)到我的 txtAmount 控件的 Amount 属性?
最佳答案
将绑定(bind)属性 UpdateSourceTrigger
设置为 PropertyChanged
<TextBox Text="{Binding Amount, StringFormat=c, UpdateSourceTrigger=PropertyChanged}" Name="txtAmount" />
关于c# - INotifyPropertyChanged 更新 ontextchange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9669933/