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

问题描述 投票:0回答:1

我直接从一张图片开始,显示我的结构,以便我可以使用图片询问我的问题。

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

当我启动应用程序时,我得到一个类似于上图的视图。在那里,我可以通过输入ChildValueTextBox来改变ChildView。但是,我仍然没有每个ChildValue与其相应的ParentViewModel属性:ChildViewModel_AChildViewModel_B之间的连接/关系。

我的问题是:如何通过改变ModelValue_AChildValue来改变ChildViewModel_A,并分别通过改变ModelValue_BChildValue来改变ChildViewModel_B

.net wpf vb.net mvvm
1个回答
0
投票

您可以将事件处理程序连接到PropertyChanged类中的ChildViewModelParentViewModel事件,并在此处设置ParentModel的属性:

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()

        AddHandler ChildViewModel_A.PropertyChanged, AddressOf OnPropertyChangedA
        AddHandler ChildViewModel_B.PropertyChanged, AddressOf OnPropertyChangedB

    End Sub

    Private Sub OnPropertyChangedA(sender As Object, e As PropertyChangedEventArgs)
        Parent.ModelValue_A = ChildViewModel_A.ChildValue
    End Sub

    Private Sub OnPropertyChangedB(sender As Object, e As PropertyChangedEventArgs)
        Parent.ModelValue_B = ChildViewModel_B.ChildValue
    End Sub
End Class
© www.soinside.com 2019 - 2024. All rights reserved.