Wpf - 绑定到集合项的问题

时间:2010-11-18 11:51:47

标签: wpf silverlight binding

这是我的简单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
}

3 个答案:

答案 0 :(得分:1)

这可能是因为视图没有捕获列表中一个元素的一个属性发生了变化。它只捕获列表更改(添加或删除元素)

private void Button_Click(object sender, RoutedEventArgs e) {

    (Persons[0] as Person).Age = 5;
    Person p = Persons.First();
    Persons.Remove(0);
    Persons.Add(p);
}

答案 1 :(得分:0)

您的代码是正确的,您已经在课堂上实施了INotifyPropertyChanged,所以一切都很好。

你确定它不会改变吗?

答案 2 :(得分:0)

我尝试了你的代码,它对我来说很有效。我甚至更改了按钮单击处理程序,因此我可以继续单击并查看TextBlock更新。

private void Button_Click(object sender, RoutedEventArgs e)
{
    (Persons[0] as Person).Age = (Persons[0] as Person).Age + 1;
}
相关问题