Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between views using DataTemplate + Triggers

I have a requirement where a where user can switch to view hierarchical data either as tree or as a text in datagrid or as FlowChart.

The user can do this by clicking a Toggle Button which say: Switch Mode. I want to do all this in such a way that it can be handled within the View only as ViewModel in all the three cases is the same.

How do I apply View to my ViewModel based on Trigger.

like image 667
Pradeep Avatar asked Jan 25 '26 07:01

Pradeep


1 Answers

If the state of which view to show is saved in some enum property you could use a ContentControl and DataTriggers for example:

<ContentControl>
    <ContentControl.Style>
        <Style TargetType="{x:Type ContentControl}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ViewMode}" Value="TreeMode">
                    <Setter Property="Content">
                        <Setter.Value>
                            <uc:TreeModeView />
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding ViewMode}" Value="GridMode">
                    <Setter Property="Content">
                        <Setter.Value>
                            <uc:GridModeView />
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

(As the style is only used in one place, by setting it directly as ContentControl.Style this will work, if you want to use it in more than one place you should set the ContentTemplate instead, because otherwise there will only be one view instance shared by all controls with the style which is not allowed by WPF (of course Content needs to be set to something for the template to be applied))

You could also bind directly to IsChecked of the ToggleButton using ElementName of course. The relevant values would then be True, False and {x:Null}.

like image 67
H.B. Avatar answered Jan 26 '26 20:01

H.B.