代码之家  ›  专栏  ›  技术社区  ›  Will

EntitySet的绑定正在显示不存在的值?

  •  0
  • Will  · 技术社区  · 15 年前

    我正在将itemsControl绑定到WPF应用程序中的EntitySet。然而,它并没有像预期的那样发挥作用。项控件的行为就像 高速缓存 绑定之间的EntitySet的内容!

    这是简化后的代码 :

    实体:

    public partial class Item : INotifyPropertyChanging, INotifyPropertyChanged
    {
        private EntitySet<Item> _Children;
        public EntitySet<Item> Children {get{return _children;}}
        /*...*/    
    }
    

    我的部分课程:

    public partial class Item
    {
        public void RemoveChild(Item child)
        {
            Children.Remove(child);
            // this finds PropertyChanged; defined in the Entity class
            SendPropertyChanged("Children");
        }
    }
    

    用户界面:

    <ItemsControl
        Name="ItemChildren"
        Background="CornflowerBlue"
        ItemsSource="{Binding Children}">
        <ItemsControl.ItemTemplate>
            <DataTemplate
                DataType="{x:Type d:Item}">
                <DockPanel>
                    <TextBlock
                        Text="{Binding Name}/>
                </DockPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    演示行为的代码 (假设2个项目,每个项目都有一个孩子):

    this.ScrewyItem = Db.Items.First();
    this.DataContext = ScrewyItem;
    return;
    

    稍后,我从实体中移除子项:

    ScrewyItem.RemoveChild(ScrewyItem.Children.First());
    return;
    

    运行此代码后,UI不会更新,并且显示该项具有所有子项。请注意,此方法调用notifypropertychanged,因此绑定应该更新!

    稍后,我们将从UI绑定中删除此项:

    this.DataContext = Db.Items.Last(); //different item
    return;
    

    稍后再将其绑定到UI

    this.DataContext = ScrewyItem;
    

    您将假定至少在此时,UI将显示正确的子列表。 这是 案件 但是!它显示了 相同的 原始显示的子项列表!

    更奇怪的是,如果我在子访问器上放置一个断点,我可以看到 当我重新绑定到UI时访问列表 列表不包含我删除的子项。

    我能看到UI执行此操作的唯一方法是在绑定之间缓存子集合的内容。

    这是怎么回事?我错过了什么????

    2 回复  |  直到 15 年前
        1
  •  0
  •   Will    15 年前

    我找到了解决办法。有点糟。

    我可以将子集合包装在绑定列表中:

    public IBindingList BindableChildren
    {
        get
        {
            return new BindingList<Item>(Children);
        }
    }
    

    然后彻底修改我的removechild方法:

    this.Children.Remove(arg);
    SendPropertyChanged("BindableChildren");
    

    这将导致UI立即更新列表,并停止显示缓存行为。

    问题仍然存在: 世界跆拳道联盟? 还有别的办法吗?

        2
  •  0
  •   Martin Liversage    15 年前

    我对此不确定,但也许 ItemsControl 正在收听来自 IBindingList INotifyCollectionChanged 而不是 INotifyPropertyChanged .