How to bind to a ListBox in a ViewModel

2019-08-28 04:08发布

问题:

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

回答1:

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.