我正在玩wpf数据绑定,我遇到了一个问题。这里是我的代码:WPF绑定到DataContext与类和子类
MainWindow.xaml
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpf"
Title="MainWindow" Height="350" Width="525">
<StackPanel Name="stackpanel">
<TextBox Name="tb1" Text="{Binding Path=A.Number}" />
<TextBox Name="tb2" Text="{Binding Path=B.Number}" />
<TextBlock Name="tbResult" Text="{Binding Path=C}" />
</StackPanel>
</Window>
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.谢谢。
感谢您的回答,但它可能以某种方式更新属性C而不实例化MySubClass – Marin