【问题标题】:Connect view with viewmodel to share an ObservableCollection将视图与视图模型连接以共享 ObservableCollection
【发布时间】:2016-07-11 10:55:23
【问题描述】:

我无法在 ListBox 对象中显示我的 ObservableCollection。我该怎么做?

这是我的基本代码:

C#

    public ObservableCollection<string> Collection { get; set; }
private void Add(Window window)
    {
            Collection = new ObservableCollection<string>();
            Collection.Add("First Item");
    }

XAML

  <ListBox ItemsSource="{Binding Collection, Mode=TwoWay}"      HorizontalAlignment="Left" Height="100" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" />

【问题讨论】:

  • 不确定那是什么,但它不是 mvvm。这是一团糟,是的,但不是 mvvm 混乱。 private void Add(Window window)此时你只是在挣扎。您应该停下来阅读 MVVM 以及它在 wpf 中的工作原理。创建几个简单的应用程序(列表框、按钮和视图模型),看看它们是如何组合在一起的。

标签: c# .net mvvm listbox


【解决方案1】:

您需要在视图模型的构造函数中初始化您的集合,或者从构造函数中调用您的Add() 方法。

顺便说一句,您的 Add() 方法没有使用它的参数。

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多