代码之家  ›  专栏  ›  技术社区  ›  Yvonnila

将两个ViewModel的属性相互绑定/关联

  •  0
  • Yvonnila  · 技术社区  · 5 年前

    我直接从一张图片开始,展示我的结构,这样我就可以用图片提问了。

    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>
    

    儿童视图模型 是这样的:

    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 通过在 TextBox . 然而,我仍然没有在两者之间建立联系/关系 儿童价值 : ChildViewModel_A ChildViewModel_B

    :我怎么换 ModelValue_A 通过改变 儿童价值 ChildViewModel_A ,分别为 ModelValue_B 儿童价值 属于

    0 回复  |  直到 5 年前
        1
  •  0
  •   mm8    5 年前

    您可以将事件处理程序连接到 PropertyChanged 大会的活动 ChildViewModel (s) 在你的 ParentViewModel 类并设置 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