c#-WPF使用类和子类绑定到DataContext
2019-11-02 14:05:16 阅读:231 来源: 互联网
标签:data-binding wpf xaml c
我在wpf中玩数据绑定,遇到问题.这是我的代码:
MainWindow.xaml
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyClass myClass = new MyClass();
myClass.A = new MySubClass();
myClass.B = new MySubClass();
stackpanel.DataContext = myClass;
}
}
MyClass.cs
class MyClass : INotifyPropertyChanged
{
private MySubClass a;
public MySubClass A
{
get { return a; }
set
{
a = value;
OnPropertyChanged(“A”);
OnPropertyChanged(“C”);
}
}
private MySubClass b;
public MySubClass B
{
get { return b; }
set
{
b = value;
OnPropertyChanged("B");
OnPropertyChanged("C");
}
}
public int C
{
get { return A.Number + B.Number; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
MySubClass.cs
class MySubClass : INotifyPropertyChanged
{
private int number;
public int Number
{
get { return number; }
set
{
number = value;
OnPropertyChanged(“Number”);
}
}
public MySubClass()
{
Number = 1;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
现在,问题是在我运行应用程序后,绑定工作正常.另外,当我在文本框中更改值A.Number和B.Number时,它们也可以更新.但是,只有在应用启动时才更新MyClass.C中的变量C,之后才更新.我需要更改什么,以便当我更改A.Number或B.Number时C更新.谢谢.
解决方法:
在更新数据模型时,是否直接在MySubClass实例上更改Number或将新的子类分配给MyClass实例?即:
myClass.A.Number = 5; // will trigger OnPropertyChanged on MySubClass, but not on MyClass
不会触发A上的OnPropertyChanged(但当然会更新A.Number).
为此,您必须执行以下操作:
MySubClass v = new MySubClass()
v.Number = 5;
myClass.A = v; // will trigger OnPropertyChanged on MyClass
更新的答案.您可以执行此操作以捕获a和b中的任何属性更改.
public MyClass()
{
a.PropertyChanged += new PropertyChangedEventHandler(UpdateC);
b.PropertyChanged += new PropertyChangedEventHandler(UpdateC);
}
void UpdateC(object sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(“C”);
}
标签:data-binding,wpf,xaml,c
来源: https://codeday.me/bug/20191102/1991948.html