我是MVVM的新手并且正在努力解决一些概念,特别是如何在视图模型之间传递值并在属性值发生变化时保持它们同步。
采用以下场景,其中有三个级别的ViewModel。
JobVM - JobItemsVM - ProductListVM
每个VM都作为其父级的属性公开。 ProductList包含ClientID属性,用于按客户端筛选可用产品列表。顶级作业还包含ClientID属性,该属性标识作业的客户端是谁。
现在,我想要做的是选择列表对顶级作业的客户端中的任何更改作出反应(即ProductList.ClientID = Job.ClientID)。
我正在使用MVVMLight。使用消息传递是一种合适的解决方案吗?
以下是所涉及的课程的一些简化代码,希望有助于解释我目前的工作方式。问题是我如何同步"具有PickList.FilterClientID属性的JobViewModel.CoreDataEntity.ClientID属性,如果用户更改了JobViewModel.CoreDataEntity.ClientID,则触发PickList.LoadList(true)。或者我应该以不同的方式接近整个事情?
CODE:
这是表示作业的业务对象,其中包含ClientID属性,该属性是分配给作业的客户端
Public Class Job
Implements BLL.Base.ICoreDataEntity
Public Property JobID Implements BLL.Base.ICoreDataEntity.RecordID
Public Property ClientID
End Class
这是作业表单的主要视图模型,用于显示和编辑作业及其相关记录。
Public Class JobViewModel
'THIS PROPERTY HOLDS THE JOB BUSINESS OBJECT
Public Property CoreDataEntity As BLL.Base.ICoreDataEntity
'THIS CONTAINS ADDITIONAL VIEWMODELS USED TO MANAGE SUBLISTS (E.G. JOB ITEMS, COMMUNICATIONS)
Public Property SecondaryDataEntities As List(Of SecondaryDataVMHelper)
Public Sub New(recordID As Integer, enableEdit As Boolean)
'POPULATE THE COREDATAENTITY WITH A JOB FROM THE DATABASE
CoreDataEntity = New BLL.Jobs.Job(recordID)
'initialize secondary view models
Me.SecondaryDataEntities.Add(New SecondaryDataVMHelper(EntityTypes.JobItem))
Me.SecondaryDataEntities.Add(New SecondaryDataVMHelper(EntityTypes.Communication))
'pass down selected details from parent record to secondary view models
'NOTE - I COULD PASS DOWN THE CLIENT ID HERE AS WELL BUT WHAT IF CLIENTID CHANGES AFTER INITIALIZED?
For Each x As SecondaryDataVMHelper In SecondaryDataEntities
x.ParentRecordID = CoreDataEntity.RecordID
x.ParentEntityType = EntityTypes.Job
x.ParentRecordDescription = CoreDataEntity.ToString()
Next
End Sub
End Class
此视图模型用于管理"子列表"与父作业相关(例如作业中的订单项)
Public Class SecondaryDataVMHelper
'THIS PROPERTY TELLS US WHAT TYPE OF RECORD WE ARE DEALING WITH IN THE SUB LIST
'FOR INSTANCE, JOB ITEMS
Public Property EntityType As EntityTypes
'AN ADDITIONAL VIEWMODEL TO MANAGE A "PICK LIST" WHICH CAN BE USED TO ADD ITEMS
'FOR INSTANCE, A PRODUCT LIST
Public Property PickList As PickListViewModel
Public Sub New(entityType As EntityTypes)
'SET UP WHAT TYPE OF DATA WE ARE DEALING WITH
Me.EntityType = entityType
'INITIALIZE THE APPROPRIATE PICK LIST
PickList = New PickListViewModel()
End Sub
End Class
最后,这个视图模型用于管理一个选择列表"显示给用户
Public Class PickListViewModel
'THE CLIENT TO FILTER THE PICK LIST BY (E.G. ONLY SHOW PRODUCTS RELATING TO THAT CLIENT)
Public Property FilterClientID As Integer
'THIS STORES THE LIST POPULATED FROM THE DATABASE WHICH IS DISPLAYED IN THE UI
Public Property Records As ObservableCollection(Of Product)
'JUST TO TRACK IF THE PICK LIST HAS BEEN LOADED
Public Property IsLoaded As Boolean
Public Sub LoadList(forceReload As Boolean)
If forceReload = False And IsLoaded Then Exit Sub
Records = BLL.Products.GetLiveList(FilterClientID) 'LOAD THE DATA, FILTERING BY CLIENT
IsLoaded = True
End Sub
End Class