OnPropertyChanged和XAML

时间:2012-10-15 11:57:35

标签: c# wpf xaml inotifypropertychanged

我正在尝试在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没有更新...... 我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要设置datacontext,以便UI知道从哪里获取绑定数据。

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    Test = "teeest";
}

答案 1 :(得分:0)

之后的Window构造函数中
  

InitializeComponents()

this.DataContext = this;