我试图了解如何更新UI,如果我有一个依赖于另一个属性的只读属性,以便更改一个属性更新两个UI元素(在这种情况下是一个文本框和一个只读文本框.例如:
public class raz : INotifyPropertyChanged
{
int _foo;
public int foo
{
get
{
return _foo;
}
set
{
_foo = value;
onPropertyChanged(this, "foo");
}
}
public int bar
{
get
{
return foo*foo;
}
}
public raz()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void onPropertyChanged(object sender, string propertyName)
{
if(this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,当修改foo时,bar不会自动更新UI.这是正确的方法吗?
我有这Bank门课:
public class Bank : INotifyPropertyChanged
{
public Bank(Account account1, Account account2)
{
Account1 = account1;
Account2 = account2;
}
public Account Account1 { get; }
public Account Account2 { get; }
public int Total => Account1.Balance + Account2.Balance;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)
Bank取决于其他类,并具有Total根据这些其他类的属性计算的属性.每当Account.Balance更改任何这些属性时,PropertyChanged都会引发Account.Balance:
public class Account : INotifyPropertyChanged
{
private int …Run Code Online (Sandbox Code Playgroud)