没有让 INotifyPropertyChanged 示例工作,我想从后面更新文本块

Not getting INotifyPropertyChanged example to work, I want to update text block from behind

我一直在查看几个 INotifyPropertyChanged 示例,但没有设法使它们中的任何一个在我的项目中工作。当我更改 属性 的值时,我的文本块中的文本没有更新,我不知道为什么。

public partial class MainWindow : Window, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public MainWindow()
        {
            InitializeComponent();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            TextTest = "essa";
        }

        private void NotifyPropertyChanged([CallerMemberName] string name="")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        private string textTest = string.Empty;

        public string TextTest {
            get { return this.TextTest; }
            set { this.textTest = value;
            NotifyPropertyChanged();
            }
        }
    }


<Window x:Class="TestProjectComboboxAndPropertyChanged.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Height="200">

        <Button Content="Click me" Click="Button_Click" Height="100" VerticalAlignment="Bottom"></Button>
        <TextBlock Text="{Binding Path=TextTest,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="55" Height="100" VerticalAlignment="Top"></TextBlock>
    </Grid>
</Window>​

您缺少绑定。在您的表单构造函数中,将表单数据上下文绑定到当前实例。

public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;

    }

这里的问题不是其他人所说的 属性 名称。根据 INotifyPropertyChanged:

的文档

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.

因此,即使您通过了 null/string.Empty,它也可以正常工作。

您遇到的问题与绑定本身有关 - 没有可供绑定使用的数据上下文。将数据上下文设置为 window 本身:

<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}">

然后你的代码将工作,除了你的 属性:

中的一个小错误
public string TextTest
{
    get { return this.TextTest; } << WILL CAUSE A STACK OVERFLOW
    set
    {
        this.textTest = value;
        NotifyPropertyChanged();
    }
}

此外,TextBlock 的绑定只需要是:

Text="{Binding TextTest}"