1

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 は更新されませんでした...何が間違っているのでしょうか?

4

2 に答える 2

2

UI がバインディングのデータを取得する場所を認識できるように、datacontext を設定する必要があります。

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    Test = "teeest";
}
于 2012-10-15T12:02:20.497 に答える
0

後の Window コンストラクターで

InitializeComponents()

置く

this.DataContext = this;

于 2012-10-15T12:02:23.247 に答える