這是我簡單的xaml,它在文本框中顯示人員集合中第一個人的年齡。點擊後,我不明白我的年齡不變。Wpf - 綁定到收集項目的問題
<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? – 2010-11-18 14:04:53
工作對我來說很好。複製/粘貼到項目,它就像一個魅力。如果你爲Age設置了一個斷點,它會觸發PropertyChanged還是爲null? – 2010-11-18 14:18:35