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:

 <GridView 
            x:Name="MyDemoList"
            Grid.Row="0"
            VerticalAlignment="Stretch"
            HorizontalAlignment="Stretch"
            ItemTemplate="{StaticResource KeyWideTemplate}"
            />

Here is my statetrigger:

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

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


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

Aucun commentaire:

Enregistrer un commentaire