我是新的WPF数据绑定。我为数据绑定测试编写了一个小程序。有两个窗户。在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“。但我不知道哪里出了问题。我也不知道是否有一种方法来检查绑定源和路径是否有效。谢谢。
发布于 2018-04-17 07:34:06
来解决这两个问题。正如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");
}https://stackoverflow.com/questions/49871856
复制相似问题