C# 在不同窗口中建立ViewModels之间的关系

C# 在不同窗口中建立ViewModels之间的关系,c#,wpf,mvvm,treeview,C#,Wpf,Mvvm,Treeview,我的程序结构如下: 主窗口: 窗口->视图模型 public ViewModel _TreeVM; private Command _newNode; public UserControl2_VM() { _newNode = new Command(NewNode_Operations); } public ViewModel TreeVM { get { return _TreeVM; } set { _TreeVM = value;

我的程序结构如下:


主窗口:

窗口->视图模型

public ViewModel _TreeVM;
private Command _newNode;

public UserControl2_VM()
{
    _newNode = new Command(NewNode_Operations);
}

public ViewModel TreeVM
{
    get { return _TreeVM; }
    set
    {
        _TreeVM = value;
        NotifyPropertyChange(() => TreeVM);
    }
}

//Command -- Adds new node
public Command NewNode { get { return _newNode; } }
private void NewNode_Operations()
{
    TreeVM.addNewNode(); //**NullReferenceException
}
UserControl1(绑定到
contentPresenter
)->ViewModel->Model

^
TreeView
(在UC1中)->ViewModel->Model

子窗口:

窗口->视图模型

public ViewModel _TreeVM;
private Command _newNode;

public UserControl2_VM()
{
    _newNode = new Command(NewNode_Operations);
}

public ViewModel TreeVM
{
    get { return _TreeVM; }
    set
    {
        _TreeVM = value;
        NotifyPropertyChange(() => TreeVM);
    }
}

//Command -- Adds new node
public Command NewNode { get { return _newNode; } }
private void NewNode_Operations()
{
    TreeVM.addNewNode(); //**NullReferenceException
}
UserControl2(绑定到
contentPresenter
)->ViewModel->Model


*子窗口是从UC1->ViewModel创建和打开的

我需要在粗体斜体视图模型之间创建一个关系。具体来说,这是子窗口的用户控件中的ViewModel,以及主窗口的用户控件中的
TreeView
的ViewModel

这是必要的,因为我想从子窗口向
树视图添加节点。问题是,尽管我在UC2->VM中为
TreeView
(UC1)->VM设置了一个属性,但我收到了一个
NullReferenceException
,因为UC2->VM无法将该属性设置为新的TV->VM之外的任何值

代码:

UserControl2->ViewModel

public ViewModel _TreeVM;
private Command _newNode;

public UserControl2_VM()
{
    _newNode = new Command(NewNode_Operations);
}

public ViewModel TreeVM
{
    get { return _TreeVM; }
    set
    {
        _TreeVM = value;
        NotifyPropertyChange(() => TreeVM);
    }
}

//Command -- Adds new node
public Command NewNode { get { return _newNode; } }
private void NewNode_Operations()
{
    TreeVM.addNewNode(); //**NullReferenceException
}
子窗口中的数据模板

<DataTemplate DataType="{x:Type project:UserControl2_VM}">
            <UC:ChildWindowUC/>
        </DataTemplate>


如何使其能够从子窗口的用户控件中的viewModel访问树视图的viewModel?

将ParentViewModel传递给ChildViewModel,以便您可以对其进行引用

DataContext = childWindowViewModel(ParentViewModel);

将父视图模型传递给子视图模型?如果你说的是传递给子窗口的视图模型(不是UserControl2->VM),我不知道该怎么做,因为CW的视图模型是使用
DataTemplate
(而不是使用
DataContext
)创建的。然后不管该DataTemplate(TreeView)的项目来源是什么,在创建父对象时,应将其传入。我怀疑DataTemplate是否正在创建ViewModel。我为您提出了
DataTemplate
的问题。它没有我知道的
itemsource
。我还认为它是在创建ViewModel,因为我没有在c#anywhere中创建它。不过这只是视图,它的ViewModel在哪里,它是如何填充的?什么是数据模板?什么的Datatemplate?那么我是在传递UC1->ViewModel,还是在传递
TreeView
->ViewModel?另外,我的子窗口看不到任何父项。将UC1的ViewModel传递给ChildWindowViewModel它看不到父项吗?为什么不呢?那没有道理。