【问题标题】:How to bind to a ListBox in a ViewModel如何绑定到 ViewModel 中的 ListBox
【发布时间】:2013-10-03 02:58:29
【问题描述】:

这是交易:我必须从Listbox 中获取SelectedItem,这是我从this question 获得的,并将其添加到另一个UserControl 中的ListBox。 ViewModels 和模型都设置好了,我只需要知道如何引用获取项目的 ListBox。

这将在 ViewModel A 下——使用接收项目的 ListBox 控制用户控件的 ViewModel。

//This is located in ViewModelA
private void buttonClick_Command()
{
    //ListBoxA.Items.Add(ViewModelB -> SelectedListItem);
}

我不明白如何获取 ListBoxA。

是ObservableCollection 还是strings?

进一步说明:由 ViewModelA 控制的 ListBoxA 将从 ViewModelB 中的 ListBoxB 接收值。我在 ViewModelA 中包含了 ViewModelB 的属性

【问题讨论】:

    标签: c# wpf mvvm listbox


    【解决方案1】:

    您需要在 ViewModelA 中有一个属性,该属性可以是任何实现 IEnumerable 的类型。我将使用一个列表:

        public const string MyListPropertyName = "MyList";
    
        private List<string> _myList;
    
        /// <summary>
        /// Sets and gets the MyList property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public List<string> MyList
        {
            get
            {
                return _myList;
            }
    
            set
            {
                if (_myList == value)
                {
                    return;
                }
    
                RaisePropertyChanging(MyListPropertyName);
                _myList = value;
                RaisePropertyChanged(MyListPropertyName);
            }
        }
    

    然后在你的 Listbox 中,你需要将 ItemsSource 设置为这个列表

    <ListBox ItemsSource="{Binding MyList}">
        .......
    </ListBox>
    

    现在在你的构造器中,用你想显示的数据填充 MyList,然后在 Add Command 上,你想放

    MyList.Add(ViewModelB.myString);  
    

    ViewModelB.myString 从您之前的问题中假设您在 ViewModelB 中有一个属性 myString 绑定到 ListBoxB 的 SelectedItem,并且您在 ViewModelA 中有对 ViewModelB 实例的引用。

    应该这样,告诉我

    更新:

    您应该在 VMA 中使用 ObservableCollection,因为该集合将被添加到。

    【讨论】:

      猜你喜欢
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2015-06-08
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多