wpf OnPropertyChanged 和 XAML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12895184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:47:11  来源:igfitidea点击:

OnPropertyChanged and XAML

c#wpfxamlinotifypropertychanged

提问by 3ka5_cat

I'm trying to specify data variable for my TextBlock at xaml:

我正在尝试在 xaml 中为我的 TextBlock 指定数据变量:

<TextBlock Name="Test11" Text="{Binding Path=Test}"></TextBlock>

I'm using OnPropertyChanged for it:

我正在使用 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");
            }
        }

And trying to set value at MainWindow constructor:

并尝试在 MainWindow 构造函数中设置值:

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

But Textblock.Text wasn't updated... What I'm doing wrong?

但是 Textblock.Text 没有更新......我做错了什么?

回答by SynerCoder

You need to set the datacontext so the UI knows where to get the data for the binding.

您需要设置数据上下文,以便 UI 知道从何处获取绑定数据。

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

回答by Klaus78

In the Window constructor after

在 Window 构造函数之后

InitializeComponents()

初始化组件()

put

this.DataContext = this;

this.DataContext = this;