I am playing with databinding in wpf and I ran into a problem. Here is my code:
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));
}
}
}
Now the problem is that the binding works fine after starting the application. Also, the A.Number and B.Number values are updated normally when I change them in the text box. But the C variable in MyClass.C is updated only when the application starts and never appears. What do I need to change to update C when A.Number or B.Number changes. Thank.
Marin source
share