超级简单的绑定示例

时间:2013-05-28 07:16:01

标签: c# wpf binding

我正在尝试做一个简单的绑定,但我遇到了一些问题。我有一个文本块和一个按钮。文本块绑定到名为“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>

1 个答案:

答案 0 :(得分:2)

您正在为名为PropertyChanged的媒体资源举办I've changed!个活动,因为您已将属性word传递给RaisePropertyChanged。您需要传递属性的名称

RaisePropertyChanged("word");

此答案假定数据上下文设置正确。如果没有,你也需要解决这个问题:

DataContext = this;