MVVM ViewModel exposing multiple views of the same collection
I'm biting off a big chunk here trying to learn MVVM, Unity, and Prism all at once (ack!). So far it's gone reasonably well but I run into stumbling blocks now and then. One of them is this:
I have a VM that defines a master-detail screen. In the detail section, I want to divide the detail lines across multiple DataGrids on a tab control. Each DataGrid contains a distinct subset of the detail lines based on the value of a property in the line ("Section"). So essentially, I read my master entity which contains a collection of detail entities. And I think I need to expose different views of this collection to the View so that the DataGrids can each bind to the proper filtered subset of the details collection. The DataGrids have to be editable. I've made a few at开发者_如何学编程tempts at exposing various levels of CollectionViews as ItemsSources for the DataGrids but nothing seems to work properly. Also, I'm thinking it would probably be best to factor out the DataGrids into a generic View since they all display the same info (just over a different subset of details) but I'm not sure how to do that. Can anyone help?
Thanks, Dennis
If I'm understanding you correctly, you have something like this:
public class MasterClass
{
public List<object> Details;
}
Where Details
is a List that contains many different types of objects, and you want to display a different View (DataGrid) for each type of object?
I would use a TabControl
with it's ItemsSource
bound to the Details
property, and then use a DataTrigger
within the TabItem to determine how the ItemTemplate (tab content) should get drawn.
Something along the lines of this:
<TabControl ItemsSource="{Binding Details}">
<TabControl.Resources>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template" Value="{StaticResource DefaultTemplate}" />
<Style.Triggers>
<DataTrigger Property="{Binding ItemType}" Value="Address">
<Setter Property="Template" Value="{StaticResource AddressTemplate}" />
</DataTrigger>
<DataTrigger Property="{Binding ItemType}" Value="Phone">
<Setter Property="Template" Value="{StaticResource PhoneTemplate}" />
</DataTrigger>
</Style>
</TabControl.Resources>
</TabControl>
That's just a rough example which would change the TabItem's template based on if the Detail.ItemType
is "Address" or "Phone". I've also done this in the past with a Converter that checks the type of object instead of needing to have a Type property on the object, which works even better.
If you're interested, I wrote a brief article here that shows a few ways of switching Views or UserControls based on ViewModel data
精彩评论