How to bind to a ListBox in a ViewModel

南笙酒味 提交于 2019-12-14 03:17:59

问题


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.



来源:https://stackoverflow.com/questions/19125096/how-to-bind-to-a-listbox-in-a-viewmodel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!