I have an object of Type MyTypeOneViewModel that is displayed in the first column of ListView and I have an object of Type MyTypeTwoViewModel that is displayed in the 2nd column of my ListView. Both types have a property of type MyNestedViewModel. Now I would like to display a different DataTemplate for each cell in the ListView depending on the actual Type of that Property. For example if the property actually holds a MyDoubleNestedViewModel I want to display a Textbox in that cell and if that property holds a MyBooleanNestedViewModel I want to display a ComboBox in that particular cell of the ListView. Note that The DataTemplate could vary in each row and column.
Can I achieve this without a TemplateSelector? WPF is able to autmatically chose the right DataTemplate based on the bound Type. But does that work in this nested scenario in a ListView too somehow?
-
Consider these options:
1. Bind directly to the sub-property.
Bind the column to the sub-property (of type
MyNestedViewModel) rather than the parent. WPF will then pick a template based on the type of the nested view model, rather than the type of the parent view model.<GridViewColumn DisplayMemberBinding="{Binding TheChildViewModel}"/>2. Include a
ContentControlin your cell template.In your grid column templates, bind a
ContentControlto the child property:<GridViewColumn.CellTemplate> <DataTemplate> <StackPanel> <Label Content="{Binding SomePropertyOnParentViewModel}"/> <ContentControl Content="{Binding TheChildViewModel}"/> </StackPanel> </DataTemplate> </GridViewColumn.CellTemplate>HTH, Kent
-
WPF can do exactly what you want.
Reference the assembly that has your data types and add a DataTemplate resource for each type you need to display.
xmlns:ui="clr-namespace:YourAssembly" <Window.Resources> <DataTemplate DataType="ui:MyDoubleNestedViewModel "> <Grid Margin="5,5,5,5" > <TextBlock Text="{Binding Path=Value}"/> </Grid> </DataTemplate> <DataTemplate DataType="ui:MyBooleanNestedViewModel "> <Grid Margin="5,5,5,5" > <ComboBox ItemsSource="{Binding Path=Items}"/> </Grid> </DataTemplate> </Window.Resources>Now this template will be used with any list or content control in this window that’s bound to your view model objects. You don’t need to specify the ItemTemplate setting.
0 comments:
Post a Comment