将两个ViewModel的属性彼此绑定/关联

时间:2019-02-15 09:18:08

标签: .net wpf vb.net mvvm

我直接从图片开始,展示我所拥有的结构,以便可以使用图片提出问题。

relation between the ViewModels

我有这样的ParentModel

Public Class ParentModel
    public Property ModelValue_A As String
    Public Property ModelValue_B As String
End Class

我有一个ParentViewModel,它有两个类型为ChildViewModel的属性。

Public Class ParentViewModel
    Public Property Parent As ParentModel
    Public Property ChildViewModel_A As ChildViewModel
    Public Property ChildViewModel_B As ChildViewModel

    Sub New
        ChildViewModel_A = New ChildViewModel()
        ChildViewModel_B = New ChildViewModel()
    End Sub
End Class

我的ParentView是这样的:

<DataTemplate>
    <StackPanel Orientation="Horizontal">
        <ContentPresenter Content="{Binding ChildViewModel_A}"/>
        <ContentPresenter Content="{Binding ChildViewModel_B}"/>
    </StackPanel>
</DataTemplate>

我的ChildViewModel是这样的:

Public Class ChildViewModel
    Private _ChildValue As String

    Public Property ChildValue As String
        Get
            Return _ChildValue
        End Get
        Set
            _ChildValue = Value
            NotifyPropertyChanged(NameOf(ChildValue))
        End Set
End Class

我的ChildView是这样的:

<DataTemplate>
    <TextBox Text="{Binding ChildValue}" />
</DataTemplate>

我的NotifyPropertyChanged方法:

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

Protected Sub NotifyPropertyChanged(info As [String])
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

启动应用程序时,我得到的视图类似于上图。在这里,我可以通过输入ChildValue的{​​{1}}来更改TextBox。但是,每个ChildView与其相应属性ChildValueParentViewModelChildViewModel_A之间仍然没有连接/关系。

我的问题是:如何更改{{1}的ChildViewModel_B来更改ModelValue_A,如何分别通过更改{{ 1}}个(共ChildValue个?

1 个答案:

答案 0 :(得分:0)

您可以将事件处理程序连接到PropertyChanged类中ChildViewModel的{​​{1}}事件,并在此事件中设置ParentViewModel的属性:

ParentModel