如何绑定到ViewModel中的列表框 [英] How to bind to a ListBox in a ViewModel
问题描述
Here's the deal: I have to take a SelectedItem
from a Listbox
, that I got from this question and add it to a ListBox
in another UserControl. The ViewModels and models are all setup, I just need to know how to refer to the ListBox that is getting the items.
这将在ViewModel A下-通过接收项目的ListBox控制用户控件的ViewModel.
This would be under ViewModel A -- the ViewModel that controls the user control with the ListBox that receives the items.
//This is located in ViewModelA
private void buttonClick_Command()
{
//ListBoxA.Items.Add(ViewModelB -> SelectedListItem);
}
我不明白如何获取ListBoxA.
I don't understand how to get ListBoxA.
会是strings
的ObservableCollection
吗?
为进一步说明:由ViewModelA控制的ListBoxA将在ViewModelB中从ListBoxB接收值.我在ViewModelA中包含了ViewModelB的属性
For further clarification: ListBoxA, controlled by ViewModelA will be receiving values from ListBoxB in ViewModelB. I have included a property for ViewModelB in ViewModelA
推荐答案
您需要在ViewModelA中拥有一个属性,该属性可以是实现IEnumerable的任何类型.我将使用一个列表:
You need to have a property in ViewModelA that can be any type that implements IEnumerable. I will use a list:
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);
}
}
然后在列表框中,将ItemsSource设置为此列表
Then in your Listbox, you need to set the ItemsSource to this list
<ListBox ItemsSource="{Binding MyList}">
.......
</ListBox>
现在,在构造器中,将要显示的数据填充到MyList中,然后在添加命令"中输入
Now in your constructer, fill MyList with the data you want to display, and on the Add Command, you want to put
MyList.Add(ViewModelB.myString);
ViewModelB.myString假定从上一个问题开始,假设在ViewModelB中,您有一个属性myString绑定到ListBoxB的SelectedItem,并且您对ViewModelA中的ViewModelB实例具有引用.
ViewModelB.myString assuming from your previous question that in ViewModelB you have a property myString bound to the SelectedItem of ListBoxB, and you have a reference to the instance of ViewModelB in ViewModelA.
这应该做到,让我知道
更新:
您应该在VMA中使用ObservableCollection,因为该集合将添加到其中.
You should be using an ObservableCollection in VMA since the collection will be added to.
这篇关于如何绑定到ViewModel中的列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!