0

私のプログラムは次のように構成されています。


メインウィンドウ:

ウィンドウ -> ビューモデル

UserControl1(にバインドcontentPresenter)->ViewModel->Model

^ TreeView(UC1 の場合) -> ViewModel -> モデル

子ウィンドウ:

ウィンドウ -> ビューモデル

UserControl2(にバインドcontentPresenter)-> ViewModel ->Model


※子ウィンドウはUC1→ViewModelから作成して開きます。

太字のイタリック体の ViewModel 間の関係を作成する必要があります。具体的には、子ウィンドウのユーザー コントロール内の ViewModel とTreeView、mainWindow のユーザー コントロール内の ViewModel です。

TreeView子ウィンドウからノードを追加したいので、これが必要です。問題は、UC2-> VM でTreeView(UC1)-> VMのプロパティをセットアップしたにもかかわらず、UC2-> VM がプロパティを新しい TV-> VMNullReferenceException以外に設定できないため、 を受け取ることです。

コード:

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子ウィンドウで:

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

TreeView子ウィンドウのユーザー コントロールの ViewModel から の viewModelにアクセスできるようにするにはどうすればよいですか?

4

1 に答える 1

2

ParentViewModel を ChildViewModel に渡して、参照できるようにします。

DataContext = childWindowViewModel(ParentViewModel);
于 2013-10-15T19:03:45.927 に答える