C# 如何绑定到ViewModel中的列表框

C# 如何绑定到ViewModel中的列表框,c#,wpf,mvvm,listbox,C#,Wpf,Mvvm,Listbox,交易是这样的:我必须从列表框中获取一个SelectedItem,然后将其添加到另一个用户控件中的列表框。ViewModels和models都已设置,我只需要知道如何引用获取项目的列表框 这将位于ViewModel A下——ViewModel通过接收项目的列表框控制用户控件 //This is located in ViewModelA private void buttonClick_Command() { //ListBoxA.Items.Add(ViewModelB -> Se

交易是这样的:我必须从
列表框
中获取一个
SelectedItem
,然后将其添加到另一个用户控件中的
列表框
。ViewModels和models都已设置,我只需要知道如何引用获取项目的列表框

这将位于ViewModel A下——ViewModel通过接收项目的列表框控制用户控件

//This is located in ViewModelA
private void buttonClick_Command()
{
    //ListBoxA.Items.Add(ViewModelB -> SelectedListItem);
}
我不知道如何得到ListBoxA

它会是一个由
字符串组成的
可观察集合吗


进一步说明:由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);
        }
    }
ViewModelB.myString根据前面的问题假设在ViewModelB中有一个绑定到ListBoxB的SelectedItem的属性myString,并且在ViewModelA中有对ViewModelB实例的引用

这应该可以,让我知道

更新:

您应该在VMA中使用ObservableCollection,因为该集合将被添加到

<ListBox ItemsSource="{Binding MyList}">
    .......
</ListBox>
MyList.Add(ViewModelB.myString);