我想将窗口中的 TextBox 绑定(bind)到作为 View 模型变量的类中包含的属性,并确保 INotifyPropertyChanged 的 PropertyChanged 事件从类传播到父级。
让我用一个例子来说明:
(Window的DataContext设置为ViewModel的一个实例)
public class ViewModel {
private OtherClass classInstance = new OtherClass();
public int Attribute {
get { return classInstance.Attribute; }
}
}
public class OtherClass : INotifyPropertyChanged {
private int _attribute;
public int Attribute {
get { return _attribute; }
set {
_attribute = value;
PropertyChanged("Attribute");
}
}
...
}
此示例中的问题是,当 Attribute 更改时,绑定(bind)的 Textbox 不会更新绑定(bind),因为我假设它正在监听 ViewModel 的 PropertyChanged 事件,而不是 OtherClass 实例的事件。
关于如何纠正这种情况的任何想法?我正在考虑将 OtherClass 的 INotifyPropertyChanged 链接到其父级的 INotifyPropertyChanged,但必须有更好的方法。
最佳答案
为什么不直接绑定(bind)到类属性而不是使用代理?
public class ViewModel {
private OtherClass classInstance = new OtherClass();
public OtherClass MyOtherClass {
get { return classInstance; }
}
}
然后在您的绑定(bind)中,您可以简单地通过 SubClass 引用该属性
{Binding MyOtherClass.Attribute}
一个简单的例子,但它有效!
背后的代码:
public partial class MainWindow : Window {
private readonly SomeClass _someClass = new SomeClass();
public MainWindow() {
InitializeComponent();
DataContext = _someClass;
}
}
public class SomeClass: INotifyPropertyChanged {
private readonly SomeSubClass _mySubClass = new SomeSubClass();
public SomeSubClass MySubClass {
get { return _mySubClass; }
}
private String _name;
public String Name {
get { return _name; }
set {
_name = value;
OnPropertyChanged("Name");
}
}
//Property Change Stuff
}
public class SomeSubClass : INotifyPropertyChanged {
private String _name;
public String Name {
get {
return _name;
}
set {
_name = value;
OnPropertyChanged("Name");
}
}
//Property Change Stuff
}
XAML:
<Window x:Class="JWC.Examples.WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<StackPanel>
<Label Content="Name" VerticalAlignment="Top" />
<TextBox Text="{Binding Name}" />
<Label Content="SubClass.Name" />
<TextBox Text="{Binding MySubClass.Name}" />
<Label Content="Bound to Name" />
<TextBlock Text="{Binding Name}" />
<Label Content="Bound to MySubClass.Name" />
<TextBlock Text="{Binding MySubClass.Name}" />
</StackPanel>
</Window>
关于wpf - 子类中的 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7575345/