视图模型公开的集合必须实现 ObservableCollection吗?与 MVVM 模式

发布于 2025-01-03 12:10:11 字数 710 浏览 0 评论 0原文

最近,我一直在尝试实现 MVVM 设计模式,但遇到了两个无法解决的问题:

  1. 据我所知,我必须在我的模型中使用ObservableCollection 类,以便将ModelView 中的它传递到View。我希望我错了,因为 View 一定不会影响 Model 结构,而且我不应该局限于这种特定的集合类型。

  2. 有什么办法可以对值类型的项目列表进行双向绑定吗?

例子:

public ObservableCollection<bool> MyBooleans
{
    get { return m_booleans; }
}
<ListView ItemsSource="{Binding MyBooleans}" ...>
    <ItemTemplate>
        ...
        <CheckBox IsChecked="{Binding}" ... />
        ...
    </ItemTemplate>
</ListView>

Recently, I have been trying to implement the MVVM design pattern, but I encountered 2 problems which I can't solve:

  1. As I see it, I must use ObservableCollection in my Model classes, in order to pass it in the ModelView to the View. I hope that I wrong, because the View must not affect the Model structure, and I shouldn't be limited to this specific collection type.

  2. Is there any way to do two-way binding with a value-type item list?

Example:

public ObservableCollection<bool> MyBooleans
{
    get { return m_booleans; }
}
<ListView ItemsSource="{Binding MyBooleans}" ...>
    <ItemTemplate>
        ...
        <CheckBox IsChecked="{Binding}" ... />
        ...
    </ItemTemplate>
</ListView>

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

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

发布评论

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

评论(1

要走干脆点 2025-01-10 12:10:11

您的视图模型应该将发生变化的集合(即添加/删除项目)公开为 ObservableCollections(或实现 INotifyCollectionChanged 的​​其他类)。这并不意味着您的模型需要公开实现此接口的集合。

您的视图模型实际上是模型上的适配器,使其更容易绑定。例如,如果您的应用程序显示推文,您的服务层可能会返回一个模型,该模型是推文列表。然后,您的视图模型会将它们插入可观察的集合中,从而导致您的视图被更新。然后,您可以在将来的某个时间通过您的服务检索新的推文(使用计时器),这些推文将再次作为列表返回。然后,您的视图模型会将这些推文添加到其 ObservableCollection 中,从而使新项目在视图中可见。

Your view model should expose collections which change (i.e. have items added / removed) as ObservableCollections (or some other class that implements INotifyCollectionChanged). This does not mean your model needs to expose collection that implement this interface.

Your view model is effectively an adapter on your model that makes it more readily bindable. As an example, if your application displays tweets, your service layer might return a model which is a list of tweets. Your view model would then insert these into an observable collection, resulting in your view being updated. You could then retrieve new tweets via your service at some point in the future (using a timer), these again would be returned as a list. Your view model would then add these tweets to its ObservableCollection resulting in the new items being visible in the view.

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