WPF - 重新加载集合(使用“new”),无需重新绑定控件

发布于 2024-09-08 01:37:39 字数 781 浏览 1 评论 0原文

想象一下以下情况:

class Repository
{
    private ObservableCollection<ModelClass> _allEntries;
    public ObservableCollection<ModelClass> AllEntries
    {
        get { return _allEntries; }
        set { _allEntries = value; }
    }
    public void RefreshDataFromDB()
    {
        _all = new ObservableCollection(GetMyData()); // whatever method there is
    }
}

现在有几个控件绑定到该集合,例如:

<ListView ItemsSource="{Binding Repository.AllEntries, ElementName=Whatever}"/>

现在的问题是,如果我调用 RefreshDataFromDB ,绑定就会丢失(至少看起来如此),因为 _all现在指向新的内存部分,并且绑定仍然使用旧的引用。在这种情况下,INotifyPropertyChanged 对我没有帮助(例如,将其放在 RefreshDataFromDB 中并没有多大帮助)。

问题是 - 您将如何处理替换集合并想要更新其使用者绑定的情况?

Imagine the following:

class Repository
{
    private ObservableCollection<ModelClass> _allEntries;
    public ObservableCollection<ModelClass> AllEntries
    {
        get { return _allEntries; }
        set { _allEntries = value; }
    }
    public void RefreshDataFromDB()
    {
        _all = new ObservableCollection(GetMyData()); // whatever method there is
    }
}

Now there are a couple of controls that bind to this collection, e.g.:

<ListView ItemsSource="{Binding Repository.AllEntries, ElementName=Whatever}"/>

The problem now is that if I call the RefreshDataFromDB the bindings get lost (at least it seems so) as the _all is now pointing to new memory part and the bindings still use the old reference. INotifyPropertyChanged does not help me in this case (e.g. putting it in RefreshDataFromDB does not help a lot).

The question would be - how would you handle a case where you replce a collection and want to update its consumers' bindings?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

穿越时光隧道 2024-09-15 01:37:39

是的;您不修改该集合,UI 绑定到该集合,然后用一个新集合替换它。

你可以这样做:

_all.Clear();
_all.AddRange(GetMyData());

希望有帮助!


或者,将 AllEntries (或 All.. 您的命名法似乎在帖子中更改了几次;))作为 DependencyProperty:

public static DependencyProperty AllEntriesProperty = DependencyProperty.Register("AllEntries", typeof(ObservableCollection), typeof(MyClass));

您还需要创建 get/set 属性,请参阅此处的示例:

http://msdn.microsoft.com/en-us/library /ms752914.aspx

Yes; you're not modifying the collection, the UI is bound to the collection, and then you replace it with a new one.

You could do this:

_all.Clear();
_all.AddRange(GetMyData());

Hope that helps!


Alternatively, make AllEntries (or All.. your nomenclature seems to change a few times on the post ;)) a DependencyProperty:

public static DependencyProperty AllEntriesProperty = DependencyProperty.Register("AllEntries", typeof(ObservableCollection), typeof(MyClass));

You'd need to make the get/set property too, see here for an example:

http://msdn.microsoft.com/en-us/library/ms752914.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文