【发布时间】:2023-03-15 21:00:07
【问题描述】:
这是我的简单 xaml,它在文本框中显示一组人员中第一个人的年龄。我不明白我点击后年龄没有变化。
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="132*" />
<RowDefinition Height="179*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Persons[0].Age}" />
<Button Grid.Row="1" Click="Button_Click">Change Age</Button>
</Grid>
这是 xaml 背后的代码:
public partial class MainWindow : Window
{
public ObservableCollection<Person> Persons { get; set; }
public MainWindow() {
Persons = new ObservableCollection<Person>();
Persons.Add(new Person{Age = -1});
DataContext = this;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) {
(Persons[0] as Person).Age = 5;
}
}
这是班上的人:
public class Person : INotifyPropertyChanged
{
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
【问题讨论】:
-
刚才我将您的代码粘贴到 Visual Studio 2010 中的 WPF 项目中时,它对我来说运行良好。您使用的是哪个版本的 WPF 和 Visual Studio?
-
对我来说工作得很好。复制/粘贴到项目,它就像一个魅力。如果您在 set 中为 Age 设置断点,它会触发 PropertyChanged 还是为 null?
标签: wpf silverlight binding