【问题标题】:Why PropertyChanged is always null?为什么 PropertyChanged 总是为空?
【发布时间】:2017-12-24 15:22:03
【问题描述】:

PropertyChanged 始终为 null,并且名称不会显示在窗口上。应该是罗马音。你知道为什么它总是为空而不显示名称吗?

我的窗户课

 public partial class MainWindow : Window, INotifyPropertyChanged
{

    string _name;
    public event PropertyChangedEventHandler PropertyChanged;

    public string PersonName
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged("PersonName");
        }
    }

    public MainWindow()
    {

        InitializeComponent();
        _name = "Adam";
        PersonName = "Roman";
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

我的 XAML

<Grid>
    <Label x:Name="Test" Width="100" Height="50" Foreground="Black" Content="{Binding PersonName, Mode=TwoWay}"></Label>
</Grid>

【问题讨论】:

  • 您在 XAML 中的何处设置 DataContext?如果不将 DataContext 设置在某个地方,您的绑定将无法正常工作。
  • 我不知道我必须设置 DataContext,现在它可以工作了,谢谢
  • 如果你在后面的代码中,这有什么意义?
  • 将 INPC 属性放入 viewmodel 类中。将 viewmodel 类的实例分配给 MainWindow 的 DataContext 属性

标签: c# wpf inotifypropertychanged


【解决方案1】:

公开public MainWindow() 添加this.DataContext = this 及其工作

看起来像

 public MainWindow()
    {
        InitializeComponent();
        _name = "Adam";
        PersonName = "Roman";
        this.DataContext = this;
    }

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2020-07-20
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多