我在WPF中有3个文本框绑定到我的业务对象的三个属性。 texbox允许用户输入三种不同的长度。
然后,我将许多文本块绑定到其他属性,这些属性显示来自3个输入的简单计算。这些属性的值在每个属性的get方法中计算如下:
public double Length1 { get; set }
public double Length2 { get; set }
public double Length3 { get; set }
public double Result1
{
get { return Length1 - Length2 - Length3; }
}
public double Result2
{
get { return Length1 + Length2 + Length3; }
}
如何在对Lengths1,2或3进行更改后更新Result1和Result2的绑定?
由于
答案 0 :(得分:3)
如果您的ViewModel正在填充INotifyPropertyChanged事件,您希望(遗憾的是)抛弃这些自动属性,并在更改Length1,Length2或Length3时引发PropertyChanged
事件。
PropertyChanged(this, new PropertyChangedEventArgs("Result1"));
private double _length1;
public double Length1 {
get { return _length1; }
set {
_length = value;
PropertyChanged(this, new PropertyChangedEventArgs("Result1"));
PropertyChanged(this, new PropertyChangedEventArgs("Result2"));
PropertyChanged(this, new PropertyChangedEventArgs("Length1"));
}
但是这很快就会很累,所以我通常会实现一个辅助方法:
void RaiseThese(params string[] properties){
foreach(string prop in properties)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
然后
public double Length1 {
get { return _length1; }
set {
_length = value;
RaiseThese("Result1", "Result2", "Length1");
}
答案 1 :(得分:2)
使用INotifyPropertyChanged并在Length1,Length2和Length3中引发Result1和Result2的事件。
private double _length1;
public double Length1
{
get { return _length1; }
set
{
if (_length1 == value) return;
_length1 = value;
OnPropertyChanged("Length1");
OnPropertyChanged("Result1");
OnPropertyChanged("Result2");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}