我正在玩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