![](/img/trans.png)
[英]How to bind a listbox to a collection within a complex type located within my ViewModel?
[英]How to bind to a ListBox in a ViewModel
這是交易:我必須從這個問題中得到的Listbox
獲取SelectedItem
,並將其添加到另一個UserControl中的ListBox
中。 ViewModel和模型都已設置,我只需要知道如何引用獲取項目的ListBox。
這將在ViewModel A下-通過接收項目的ListBox控制用戶控件的ViewModel。
//This is located in ViewModelA
private void buttonClick_Command()
{
//ListBoxA.Items.Add(ViewModelB -> SelectedListItem);
}
我不明白如何獲取ListBoxA。
會是strings
的ObservableCollection
嗎?
為了進一步說明:由ViewModelA控制的ListBoxA將在ViewModelB中從ListBoxB接收值。 我在ViewModelA中包含了ViewModelB的屬性
您需要在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);
}
}
然后在您的列表框中,需要將ItemsSource設置為此列表
<ListBox ItemsSource="{Binding MyList}">
.......
</ListBox>
現在,在構造器中,將要顯示的數據填充到MyList中,然后在“添加命令”上輸入
MyList.Add(ViewModelB.myString);
ViewModelB.myString假定從上一個問題開始,假設在ViewModelB中您有一個屬性myString綁定到ListBoxB的SelectedItem,並且您對ViewModelA中的ViewModelB實例具有引用。
應該這樣做,讓我知道
更新:
您應該在VMA中使用ObservableCollection,因為該集合將添加到其中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.