Search code examples
wpflayoutgriditemscontrol

Dynamically Display Grid Content


I have 3 different layouts (similar to I guess what you would call Skins but the layouts are hugely different, not just changes to colors and fonts) which I have developed for my application. The layouts are used for displaying the same data, but in a completely different format. Each of these layouts have been constructed within their own Grid.

I want my application to decide which layout to display dynamically based on a string value available at runtime.

What's the best way to get a parent Grid to display a Child Grid dynamically?

I'm trying to find some sort of magical DataTemplate / DataBinding / Templating method but just can't seem to find the best way. Alternatively, should I be looking at a different method of displaying these different layouts? Like an ItemsControl or similar?

Ben


Solution

  • I usually use a ContentControl and DataTrigger to determine what ContentTemplate to use.

    For example,

    <ContentControl Content="{Binding MyViewModel}">
    
        <ContentControl.Resources>
            <DataTemplate x:Key="DefaultTemplate">
                <TextBlock Text="DefaultTemplate" />
            </DataTemplate>
    
            <DataTemplate x:Key="TemplateA">
                <TextBlock Text="Template A" />
            </DataTemplate> 
    
            <DataTemplate x:Key="TemplateB">
                <TextBlock Text="Template B" />
            </DataTemplate>
        </ContentControl.Resources>
    
         <ContentControl.Style>
             <Style TargetType="{x:Type ContentControl}">
                 <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
                 <Style.Triggers>
                     <DataTrigger Binding="{Binding SelectedView}" Value="ViewA">
                         <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
                     </DataTrigger>
                     <DataTrigger Binding="{Binding SelectedView}" Value="ViewB">
                         <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
                     </DataTrigger>
                 </Style.Triggers>
             </Style>
         </ContentControl.Style>
    
     </ContentControl>