【问题标题】:OnPropertyChanged and XAMLOnPropertyChanged 和 XAML
【发布时间】:2012-10-15 11:57:35
【问题描述】:

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

【问题讨论】:

    标签: c# wpf xaml inotifypropertychanged


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      在Window构造函数之后

      初始化组件()

      this.DataContext = this;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-29
        • 1970-01-01
        • 2014-02-16
        • 2018-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多