我正在尝试在xaml上为我的TextBlock指定数据变量:
<TextBlock Name="Test11" Text="{Binding Path=Test}"></TextBlock>
我正在使用OnPropertyChanged:
public partial class MainWindow : Window, INotifyPropertyChanged
private string _test;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public string Test
{
get
{
return _test;
}
set
{
_test = value;
OnPropertyChanged("Test");
}
}
尝试在MainWindow构造函数中设置值:
public MainWindow()
{
InitializeComponent();
Test = "teeest";
}
但是Textblock.Text没有更新...... 我做错了什么?
答案 0 :(得分:2)
您需要设置datacontext,以便UI知道从哪里获取绑定数据。
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Test = "teeest";
}
答案 1 :(得分:0)
在
之后的Window构造函数中InitializeComponents()
把
this.DataContext = this;