2

I'm trying to toggle a control between compact and expanded states based on the screen size. To do this I'm using visual states to change the control's template:

<UserControl>
    <Grid>
        <Grid.Resources>
            <ControlTemplate x:Key="CompactMenuTemplate" TargetType="HeaderedItemsControl">
                <Border>
                    <StackPanel>
                        <Image icon-menu.png" Cursor="Hand"/>
                        <Popup>
                            <Border Background="Blue">
                                <ItemsPresenter />
                            </Border>
                        </Popup>
                    </StackPanel>
                </Border>
            </ControlTemplate>

            <ControlTemplate x:Key="ExpandedMenuTemplate" TargetType="HeaderedItemsControl">
                <StackPanel Orientation="Horizontal" IsItemsHost="True" />
            </ControlTemplate>
        </Grid.Resources>

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="ScreenSizeGroups">
                <VisualState x:Name="Wide" />
                <VisualState x:Name="Small">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames 
                                          Storyboard.TargetName="linkItems" 
                                          Storyboard.TargetProperty="Template">
                            <DiscreteObjectKeyFrame KeyTime="0" 
                                          Value="{StaticResource CompactMenuTemplate}" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <HeaderedItemsControl x:Name="linkItems"
                              Template="{StaticResource ExpandedMenuTemplate}">
            <Button Content="link #1" />
            <Button Content="link #2" />
            <Button Content="link #3" />
        </HeaderedItemsControl>
    </Grid>
</UserControl>

This results in an InvalidOperationException when the visual state changes:

This Freezable cannot be frozen.

Is there some trick to make this work the way I want it to, or do I need to take a different approach?

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • 1
    I don't think you can swap like that at runtime with the ControlTemplate, I'd have to look to be sure but you may be thinking towards setting your ControlTemplate and using the [ContentControl.ContentTemplateSelector](https://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contenttemplateselector.aspx) route instead. That might explain the weird freezable it's whining about. – Chris W. Nov 09 '15 at 19:22

0 Answers0