C# 我的属性不使用[CallerMemberName]更新

C# 我的属性不使用[CallerMemberName]更新,c#,wpf,inotifypropertychanged,callermembername,C#,Wpf,Inotifypropertychanged,Callermembername,诚然,我是wpf的新手。但我花了一些时间在谷歌上搜索这一切,我被难住了 本质上,每当模型值更改时,我都希望使用绑定更新UI中的TextBlock 这就是我的模型: using System.ComponentModel; using System.Runtime.CompilerServices; namespace WpfApplication1 { public class MyModel : INotifyPropertyChanged { protect

诚然,我是wpf的新手。但我花了一些时间在谷歌上搜索这一切,我被难住了

本质上,每当模型值更改时,我都希望使用绑定更新UI中的TextBlock

这就是我的模型:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfApplication1
{
    public class MyModel : INotifyPropertyChanged
    {
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return false;
            }

            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        public string MyField { get; set ; } 
    }
}

当我按下按钮时,UI上的文本不会更改。

在代码隐藏中创建的实例与在xaml中指定的实例不同

将按钮单击事件更改为

private void Button_Click(object sender, RoutedEventArgs e)
{
    var model = this.DataContext as MyModel;
    model.MyField = "has worked";
}
以及将xaml中的绑定

<TextBlock Text="{Binding MyField}"></TextBlock>

在代码隐藏中创建的实例与在xaml中分配的实例不同

将按钮单击事件更改为

private void Button_Click(object sender, RoutedEventArgs e)
{
    var model = this.DataContext as MyModel;
    model.MyField = "has worked";
}
以及将xaml中的绑定

<TextBlock Text="{Binding MyField}"></TextBlock>

非常感谢您给出如此清晰简单的答案。我可以在3分钟内接受。顺便问一下,使用静态类/属性可以实现同样的效果吗?静态类不能实现接口INotifyPropertyChanged。使用单例实例将{x:Static MyClass.instance.Property}.ta“静态地”绑定以进行应答。我知道singleton类是什么,但不确定如何在上下文中将其应用于此?另外,您不应该对按钮使用事件处理程序,请阅读有关如何将命令从viewmodel绑定到ui元素的内容。re:command谢谢。接下来我要看一看:)为什么不喜欢使用事件处理程序?非常感谢您给出了如此清晰简单的答案。我可以在3分钟内接受。顺便问一下,使用静态类/属性可以实现同样的效果吗?静态类不能实现接口INotifyPropertyChanged。使用单例实例将{x:Static MyClass.instance.Property}.ta“静态地”绑定以进行应答。我知道singleton类是什么,但不确定如何在上下文中将其应用于此?另外,您不应该对按钮使用事件处理程序,请阅读有关如何将命令从viewmodel绑定到ui元素的内容。re:command谢谢。接下来我要看一看:)为什么不喜欢使用事件处理程序?
private string myField;

public string MyField
{
    get { return this.myField; }
    set { this.SetProperty(ref this.myField, value); }
}