lundi 10 avril 2017

Using state triggers to change your ItemTemplate in a GridView or ListView [XAML][UWP]

Here is another very quick post about State Triggers and why they are awesome, recently I needed to have  2 very different visuals depending on what size my application was and on what page my application was. Usually I set my StateTriggers inside my UserControl however today this was not an option because of the design on my application.

My best option was to change the ItemTemplate on my gridview using statetriggers, I needed to have 2 different states depending I was in Narrow or Wide mode.

Here is the Gridview:

            ItemTemplate="{StaticResource KeyWideTemplate}"

Here is my statetrigger:

            <VisualStateGroup x:Name="VisualStateGroup">
                <VisualState x:Name="VisualStateNarrow">
                        <AdaptiveTrigger x:Name="VisualStateNarrowTrigger" MinWindowWidth="450" />
                        <Setter Target="MyDemoList.(ItemsControl.ItemTemplate)" Value="{StaticResource KeyNarrowTemplate}" />

                <VisualState x:Name="VisualStateNormal">
                        <AdaptiveTrigger x:Name="VisualStateNormalTrigger" MinWindowWidth="600" />
                        <Setter Target="MyDemoList.(ItemsControl.ItemTemplate)" Value="{StaticResource KeyWideTemplate}" />

This means that when the application is in wide mode the KeyWideTemplate will be used in the GridView template

and when the application is in narrow mode the KeyNarrowTemplate will be used.

Happy coding.
Github sample here