简体   繁体   中英

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.

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);
}

I don't understand how to get ListBoxA.

Would it be an ObservableCollection of strings ?

For further clarification: ListBoxA, controlled by ViewModelA will be receiving values from ListBoxB in ViewModelB. I have included a property for ViewModelB in ViewModelA

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);
        }
    }

Then in your Listbox, you need to set the ItemsSource to this list

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

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 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.

This should do it, let me know

Update:

You should be using an ObservableCollection in VMA since the collection will be added to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM