我是WPF数据绑定的新手。我写了一个用于数据绑定测试的小程序。有2个窗户。 在Window1.xaml.cs中,
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
string test = "aaa";
string Test
{
get { return test; }
set { test = value; }
}
在MainWindow.xaml.cs中,
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
Window1 W1 = new Window1();
textBlock.DataContext = this;//data-binding source
textBlock1.DataContext = W1;//data-binding source
}
public event PropertyChangedEventHandler PropertyChanged;
private int a;
public int A
{
get { return a; }
set { a = value; }
}
private void button_Click(object sender, RoutedEventArgs e)
{
a++; //why does not it update the value in the UI?
}
}
最后在MainWindow.xaml:
<Button x:Name="button" Click="button_Click"/>
<TextBlock x:Name="textBlock" Text="{Binding A}"/>
<TextBlock x:Name="textBlock1" Text="{Binding Test}"/> //Why does not it work?
我想在单击按钮时更新MainWindow UI,以及从另一个窗口绑定字符串类型值“aaa”。但我不知道哪里出了问题。我也不知道是否有办法检查绑定源和路径是否有效。感谢。
答案 0 :(得分:1)
解决这两个问题。正如Sinatr和Alex所说,
首先,
public string Test
{
get { return test; }
set { test = value; }
}
其次,
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyname)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyname));
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
a++; //why does not it update the value in the UI?
OnPropertyChanged("A");
}