1

我正在尝试做一个简单的绑定,但我遇到了一些问题。我有一个文本块和一个按钮。文本块绑定到一个名为“word”的属性。当您按下按钮时,单词的值会发生变化,我想自动更新文本块。这是一个经典的例子,请解释我做错了什么:

namespace WpfApplication5
{
     public partial class MainWindow : Window, INotifyPropertyChanged
    {

        private string _word;

        public string word
        {
            get { return _word; }
            set
            {
                _word= value;
                RaisePropertyChanged(word);
            }
        }

        private void change_Click(object sender, RoutedEventArgs e)
        {
            word= "I've changed!";
        }


        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion


    }
}

我的 XAML 与绑定:

<Window x:Class="WpfApplication5.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>
        <TextBlock HorizontalAlignment="Left" Margin="210,152,0,0" TextWrapping="Wrap" Text="{Binding word}" VerticalAlignment="Top"/>
        <Button x:Name="change" Content="Change" HorizontalAlignment="Left" Margin="189,235,0,0" VerticalAlignment="Top" Width="75" Click="change_Click"/>
    </Grid>
</Window>
4

1 回答 1

2

PropertyChanged您正在为名为 的属性引发事件I've changed!,因为您将属性的word传递给RaisePropertyChanged。您需要传递属性的名称:

RaisePropertyChanged("word");

此答案假定数据上下文设置正确。如果没有,您也需要修复它:

DataContext = this;
于 2013-05-28T07:19:06.260 回答