我有 2 个视图模型,
viewmodel 绑定到 view
class A : INotifyPropertyChanged
{
public A(){}
private bool _propertya;
public bool PropertyA
{
get{return _propertya;}
set{_propertya=value; onPropertyChanged("PropertyA");}
}
private void onPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
还有另一个视图模型,其中我的属性链接到另一个视图
class B : INotifyPropertyChanged
{
public B(){}
private bool _propertyb;
public bool PropertyB
{
get{ return _propertyb;}
set{_propertyb=value; onPropertyChanged("PropertyB");}
}
private void onPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
当 PropertyB 更改时,我想从另一个视图模型检查 PropertyA 的值并根据条件返回 bool 值。我如何从 B 类中的另一个视图模型获取 PropertyA 的实例
变化:
public static class SharedClass
{
public static event EventHandler PropertyAChanged;
public static void UpdatePropertyA(bool NewValue)
{
PropertyAChanged?.Invoke(NewValue, EventArgs.Empty);
}
}
class A : INotifyPropertyChanged
{
public A() { }
private bool _propertya;
public bool PropertyA
{
get { return _propertya; }
set
{
_propertya = value;
onPropertyChanged("PropertyA");
SharedClass.UpdatePropertyA(value);
}
}
private void onPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
class B : INotifyPropertyChanged
{
public B()
{
SharedClass.PropertyAChanged += SharedClass_PropertyAChanged;
}
private void SharedClass_PropertyAChanged(object? sender, EventArgs e)
{
if(sender is not null and bool NewValue_PropertyA)
{
//Access new Value of PropertyA by (NewValue_PropertyA)
//Example if (NewValue_PropertyA is true) { ... }
...
}
}
private bool _propertyb;
public bool PropertyB
{
get { return _propertyb; }
set { _propertyb = value; onPropertyChanged("PropertyB"); }
}
private void onPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}