我正在尝试实现数据绑定(bind),并在单击某个按钮后更新 TextBox 的文本。
XAML:
<TextBox Text="{Binding Path=Output}" />
代码:
public MainWindow()
{
InitializeComponent();
DataContext = Search;
Search.Output = "111";
}
public SearchClass Search = new SearchClass();
private void button1_Click(object sender, RoutedEventArgs e)
{
Search.Output = "222";
}
public class SearchClass
{
string _output;
public string Output
{
get { return _output; }
set { _output = value; }
}
}
当我执行该程序时,我看到“111”,因此来自 MainWindow() 的绑定(bind)有效,但是如果我单击一个按钮 - TextBox 中的文本不会更新(但在调试器中我看到 button1_Click 已执行Search.Output 现在等于“222”)。我做错了什么?
请您参考如下方法:
您应该在 SearchClass 中实现 INotifyPropertyChanged,然后在 setter 中引发事件:
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string Output
{
get { return _output; }
set
{
_output = value;
PropertyChanged(this, new PropertyChangedEventArgs("Output"));
}
}
如果我没理解错的话,SearchClass 是您的 TextBlock 的 DataContext。在这种情况下,如上实现会有所帮助。
当 WPF 将某个类视为绑定(bind)源时 - 它会尝试将其转换为 INotifyPropertyChanged 并订阅 PropertyChanged 事件。当引发事件时 - WPF 更新与发件人关联的绑定(bind)(PropertyChanged 的第一个参数)。它是使绑定(bind)工作如此顺利的主要机制。
