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

时间:2015-04-18 20:26:55

标签: c# .net-4.5 inotifypropertychanged

我一直在查看几个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>​

2 个答案:

答案 0 :(得分:1)

这里的问题不是其他人所说的财产名称。根据{{​​1}}的文档:

  

PropertyChanged事件可以通过使用null或String.Empty作为PropertyChangedEventArgs中的属性名来指示对象上的所有属性都已更改。

所以即使您通过了INotifyPropertyChanged / null,它也能完美地运作。

您遇到的问题是绑定本身 - 没有用于绑定的数据上下文。要将数据上下文设置为窗口本身:

string.Empty

然后您的代码将起作用,但属性中的小错误除外:

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

此外,public string TextTest { get { return this.TextTest; } << WILL CAUSE A STACK OVERFLOW set { this.textTest = value; NotifyPropertyChanged(); } } 的绑定只需要:

TextBlock

答案 1 :(得分:0)

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

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

    }