【问题标题】:Wpf - problem with binding to a collection itemWpf - 绑定到集合项的问题
【发布时间】: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


【解决方案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);
}

【讨论】:

  • 但这不是必需的,因为 Person 类本身实现了 INotifyPropertyChange。 (实际上,原始代码在我的系统上运行得很好。)这里发生的只是单个 Person 对象的 Age 属性正在发生变化——甚至不需要列表级别的通知。事实上,当我用 List 替换 ObservableCollection 时,它会继续工作 - Person 引发的属性更改通知工作正常。
  • Person 对象可能正在发送 INotifyPropertyChange。但是您并没有绑定到 Person,而是绑定到 ObservableCollection 的第一项,因此它只捕获 Collection 中的添加或删除。
  • 你可以做一些事情,让每个Person 附加一个触发Persons 集合更改事件的 PropertyChange 事件
【解决方案2】:

你的代码是正确的,你已经在你的类上实现了 INotifyPropertyChanged 所以一切都应该很好。

你确定它没有改变吗?

【讨论】:

    【解决方案3】:

    我尝试了您的代码,它对我来说非常有效。我什至更改了按钮单击处理程序,以便我可以继续单击并查看 TextBlock 更新。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多