超级简单的绑定示例
本文关键字:绑定 超级简单 | 更新日期: 2023-09-27 18:15:43
我试图做一个简单的绑定,但我有一些问题。我有一个文本块和一个按钮。textblock被绑定到一个名为"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>
您正在为名为I've changed!
的属性引发PropertyChanged
事件,因为您将属性word
的值传递给RaisePropertyChanged
。您需要传递属性的名称:
RaisePropertyChanged("word");
这个答案假设数据上下文设置正确。如果没有,您也需要修复它:
DataContext = this;