我的属性未使用[CallerMemberName]

时间:2016-01-07 12:54:10

标签: c# wpf inotifypropertychanged callermembername

不可否认,我是wpf的新手。但我花了一些时间谷歌搜索这一切,我很难过。

本质上我想在我的模型值发生变化时使用Binding在我的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 ; } 
    }
}

这是我的用户界面:

 <Window x:Class="WpfApplication1.MainWindow"
        xmlns:viewModels="clr-namespace:WpfApplication1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        d:DataContext="{d:DesignInstance viewModels:MyModel, IsDesignTimeCreatable=True}"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <viewModels:MyModel></viewModels:MyModel>
    </Window.DataContext>
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding  MyModel.MyField}"></TextBlock> 
          <Button Content="Click Me!" Click="Button_Click" />  
        </StackPanel>
    </Grid>
</Window>

这是我背后的代码:

使用System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public MyModel myModel = new MyModel();


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            myModel.MyField = "has worked";
        }
    }
}

当我按下按钮时,UI上的文字没有变化..?

1 个答案:

答案 0 :(得分:3)

您在后面的代码中创建的实例与您在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>

在您的viewmodel中,您没有调用notify属性已更改。因此,创建一个私有字段并修改属性,如下所示。

private string myField;

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