How to create Master Detail view with two user controls in MVVM?
I am little confused about how to create Master Detail view with two different user controls.
There are three choices,
Choice 1
CustomerMasterView + CustomerMasterViewModel
CustomerDetailView + CustomerDetailViewModel
And keep both View Models in App.Resources
But by doing this, binding becomes complex with all static resources source markup code.
Choice 2
CustomerViewModel
CustomerMasterView
CustomerDetailView
Both views share same ViewModel via App.Resources, well even with the binding code has too many items.
Choice 3
CustomerMasterView + CustomerMasterViewModel
CustomerDetailView + CustomerDetailViewModel
Both view's have DataContext set to their corresponding ViewModel. Now here is the l开发者_开发知识库ittle issue, CustomerMasterView has Selector (ListBox or DataGrid or whatever), whose SelectedItem needs to be bound to CustomerDetailViewModel's "Customer" Property as two way binding.
Does it look good?
<!-- CustomerMasterView -->
<ListBox
ItemsSource="{Binding CustomerList}"
SelectedItem="{Binding DataContext.Customer,ElementName=customerDetailView}"
/>
<local:CustomerDetailView
x:Name="customerDetailView"
/>
But by doing this, I am defying purpose of ViewModel as it adds more dependency in my UI code.
Which one is most preferred way or is there any other way? Should I create nested View Models?
I am also trying to learn Prism, and I have little confusion of how to do this right, any help will be appriciated.
The simplest appraoch in my opinion would be to have a single view model, with two UserControls.
Your ViewModel would have your list of customers, as well as a "ActiveCustomer" or "SelectedCustomer". Your MasterView (with the DataContext set to you ViewModel), would contain your list, wired up like this:
<ListBox ItemsSource="{Binding Customers}" SelectedItem="{Binding ActiveItem, Mode=TwoWay}" />
Your MasterView will also include your DetailsView (another UserControl). It looks like this:
<views:DetailsUserControl DataContext="{Binding ActiveItem}" />
You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to implement a Master/Detail scenario with two Views (separate UserControls) and two ViewModels.
精彩评论