2013-11-01 6 views
2

У меня возникли трудности при решении проблемы Visual State после перехода на VS2013 и приложения для Windows Store для 8.1. У меня есть приложение с кнопкой App About App, которая выводит пользователя на страницу About. Работает отлично. Я хочу, чтобы на странице «О программе» панель стека изменила ориентацию, когда представление изменилось на «Портрет». Работал над этим часами и читал бесчисленные сайты с точными копиями этого кода, но мой не будет работать. Есть идеи?Windows Store Apps 8.1 и VisualStateManager

Вот C# код на AboutPage.cs:

private void AboutPage_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     if (e.NewSize.Height/e.NewSize.Width >= 1) 
     { 
      VisualStateManager.GoToState(this, "Portrait", true); 
     } 
     else 
     { 
      VisualStateManager.GoToState(this, "DefaultLayout", true); 
     } 
    } 

Вот XAML на AboutPage.xaml:

<Page 
x:Name="pageRoot" 
x:Class="xxxxxxxxxxxxxxxxx.AboutPage" 
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:xxxxxxxxxxxxxxxxxx" 
xmlns:common="using:xxxxxxxxxxxxxxx.Common" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" SizeChanged="AboutPage_SizeChanged"> 

<Page.Resources> 
    <!-- TODO: Delete this line if the key AppName is declared in App.xaml --> 
    <!--<x:String x:Key="AppName">xxxxxxxxxxxxxxxxxxx</x:String>--> 
</Page.Resources> 

<!-- 
    This grid acts as a root panel for the page that defines two rows: 
    * Row 0 contains the back button and page title 
    * Row 1 contains the rest of the page layout 
--> 
<Grid x:Name="pageMainGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <Grid.ChildrenTransitions> 
     <TransitionCollection> 
      <EntranceThemeTransition/> 
     </TransitionCollection> 
    </Grid.ChildrenTransitions> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="140"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <!-- Back button and page title --> 
    <Grid x:Name="pageHeaderGrid"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="120"/> 
      <ColumnDefinition Width="*"/> 
     </Grid.ColumnDefinitions> 

     <StackPanel 
      x:Name="headerStackPanel" 
      Grid.ColumnSpan="3" 
      Background="#FF4617B4" 
      Orientation="Horizontal" > 
      <Button 
       x:Name="backButton" 
       Margin="39,59,39,0" 
       Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
       Style="{StaticResource NavigationBackButtonNormalStyle}" 
       VerticalAlignment="Top" 
       AutomationProperties.Name="Back" 
       AutomationProperties.AutomationId="BackButton" 
       AutomationProperties.ItemType="Navigation Button"/> 
      <TextBlock 
       x:Name="pageTitle" 
       Style="{StaticResource HeaderTextBlockStyle}" 
       Grid.Column="1" 
       IsHitTestVisible="false" 
       TextWrapping="NoWrap" 
       VerticalAlignment="Bottom" 
       Margin="0,0,30,40" 
       Text="{StaticResource AppName}"/> 
     </StackPanel>    
    </Grid> 

    <Grid 
     x:Name="pageContentGrid" 
     Grid.Row="1" 
     Visibility="Visible"> 

     <Grid.RowDefinitions> 
      <RowDefinition Height="20*"/> 
      <RowDefinition Height="142*"/> 
     </Grid.RowDefinitions> 

     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="150*"/> 
      <ColumnDefinition Width="372*"/> 
      <ColumnDefinition Width="150*"/> 
     </Grid.ColumnDefinitions> 

     <TextBlock 
      Grid.Column="1" 
      HorizontalAlignment="Stretch" 
      VerticalAlignment="Stretch" 
      Margin="0,0,0,0" 
      TextAlignment="Center" 
      Text="About" 
      FontSize="48" 
      FontFamily="Segoe UI"/> 

     <ScrollViewer 
      BorderThickness="0,2,0,0" 
      BorderBrush="DarkGray" 
      Grid.Row="1" 
      Grid.Column="1" 
      ScrollViewer.VerticalScrollBarVisibility="Hidden" 
      Margin="0"> 

      <StackPanel 
       Margin="40"> 

       <TextBlock 
        Text="xxxxxxxxxxxxxxxxxx" 
        FontSize="34" /> 

       <TextBlock 
        Text="by xxxxxxxxxx" 
        FontSize="24"/> 

       <StackPanel 
        Orientation="Vertical" 
        Margin="0,25,0,0"> 

        <TextBlock 
         Margin="0,6,0,0" 
         Padding="0,0,0,0" 
         Text="Website:" 
         FontSize="24" 
         VerticalAlignment="Center"/> 

        <HyperlinkButton 
         Margin="0,0,0,0" 
         Padding="-5,0,0,0" 
         FontSize="20" 
         NavigateUri="http://www.xxxxxxxxxxxxxx.com" 
         HorizontalAlignment="Left" 
         VerticalAlignment="Center" 
         Content="www.xxxxxxxxxxxxxxxxxx.com" /> 

       </StackPanel> 

       <StackPanel 
        x:Name="emailStack" 
        Orientation="Vertical" 
        Margin="0,25,0,0"> 

        <TextBlock 
         Margin="0,4,0,0" 
         Padding="0,0,0,0" 
         Text="Support Email:" 
         FontSize="24" 
         VerticalAlignment="Center"/> 

        <HyperlinkButton 
         Margin="0,0,0,0" 
         Padding="-5,0,0,0" 
         FontSize="20" 
         NavigateUri="mailto:[email protected]" 
         HorizontalAlignment="Left" 
         VerticalAlignment="Center" 
         Content="[email protected]" /> 

       </StackPanel> 

       <TextBlock 
        Margin="0,30,0,0" 
        Text="Feedback:" 
        FontSize="24"/> 

       <TextBlock 
        TextWrapping="Wrap" 
        Margin="0,10,0,10" 
        FontSize="20" > 

        Please take a few moments to rate and review my application. 
        Every little bit of encouragement and/or constructive feedback 
        is appreciated. 
        <LineBreak /><LineBreak /> 
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 

       </TextBlock> 
      </StackPanel> 
     </ScrollViewer> 

     <Rectangle 
      Grid.Row="0" 
      Grid.Column="0" 
      Grid.RowSpan="2" 
      HorizontalAlignment="Stretch" 
      Fill="DarkGray" /> 

     <Rectangle 
      Grid.Row="0" 
      Grid.Column="2" 
      Grid.RowSpan="2" 
      HorizontalAlignment="Stretch" 
      Fill="DarkGray" />   
    </Grid> 

    <VisualStateManager.VisualStateGroups> 
     <VisualStateGroup> 
      <VisualState x:Name="DefaultLayout"> 
       <Storyboard> 
       </Storyboard> 
      </VisualState> 

      <VisualState x:Name="Portrait"> 
       <Storyboard> 
        <ObjectAnimationUsingKeyFrames 
         Storyboard.TargetProperty="(StackPanel.Orientation)" 
         Storyboard.TargetName="emailStack"> 
         <DiscreteObjectKeyFrame KeyTime="0"> 
          <DiscreteObjectKeyFrame.Value> 
           <Orientation>Horizontal</Orientation> 
          </DiscreteObjectKeyFrame.Value> 
         </DiscreteObjectKeyFrame> 
        </ObjectAnimationUsingKeyFrames> 
       </Storyboard> 
      </VisualState> 
     </VisualStateGroup> 
    </VisualStateManager.VisualStateGroups> 

</Grid>  

ответ

1

Ввод VisualStateManager внутри основного контроля содержания ваш Page (обычно Grid или StackPanel) должен изменить макет вашего AppBar. Попробуйте.

<Page 
    ... 
    SizeChanged="Page_SizeChanged"> 

    <Page.BottomAppBar> 
     <AppBar> 
      <StackPanel 
       x:Name="emailStack" 
       Orientation="Vertical" 
       Margin="0,25,0,0"> 

       <TextBlock 
        Margin="0,4,0,0" 
        Padding="0,0,0,0" 
        Text="Support Email:" 
        FontSize="24" 
        VerticalAlignment="Center"/> 

       <HyperlinkButton 
        Margin="0,0,0,0" 
        Padding="-5,0,0,0" 
        FontSize="20" 
        NavigateUri="mailto:[email protected]" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Center" 
        Content="[email protected]" /> 
      </StackPanel> 
     </AppBar> 
    </Page.BottomAppBar> 

    <Grid> 
     <VisualStateManager.VisualStateGroups> 
      <VisualStateGroup> 
       <VisualState x:Name="DefaultLayout"> 
        <Storyboard> 
        </Storyboard> 
       </VisualState> 

       <VisualState x:Name="Portrait"> 
        <Storyboard> 
         <ObjectAnimationUsingKeyFrames 
          Storyboard.TargetProperty="(StackPanel.Orientation)" 
          Storyboard.TargetName="emailStack"> 
          <DiscreteObjectKeyFrame KeyTime="0"> 
           <DiscreteObjectKeyFrame.Value> 
            <Orientation>Horizontal</Orientation> 
           </DiscreteObjectKeyFrame.Value> 
          </DiscreteObjectKeyFrame> 
         </ObjectAnimationUsingKeyFrames> 
        </Storyboard> 
       </VisualState> 
      </VisualStateGroup> 
     </VisualStateManager.VisualStateGroups> 
    </Grid> 
</Page> 
+0

Я отредактировал свое оригинальное сообщение с измененным кодом, который вы предложили. Большое спасибо за помощь, но ваше предложение не помогло. – dmiannay

+0

Я забыл, что 'StackPanel' был внутри' AppBar'. Я обновил свой ответ. – kiewic

+0

На самом деле, мой StackPanel не находится в AppBar. Я обновил исходное сообщение выше, чтобы показать все содержимое файла AboutPage.xaml, чтобы вы могли видеть всю схему. Изменение ориентации этого StackPanel - это просто тест, чтобы проверить, могу ли я заставить это работать. На самом деле есть что-то более активное, что я хочу сделать, но я просто хочу, чтобы VisualStateManager работал правильно. Спасибо за вашу помощь! – dmiannay

3

Это должно быть выделено, потому что это ответ:

Ok, наконец ... проблема решена! Трюк состоял в том, чтобы найти блок XAML VisualStateManager сразу после Grid, который содержит элемент управления, который вы хотите изменить, при изменении размера экрана. Я изменил блок AboutPage XALM в своем исходном сообщении, чтобы показать правильную конфигурацию.

Это потрясающее изменение от .NET 4.5.1, где вы можете поместить VisualStateManager перед элементами управления, которые выполняются.

Смежные вопросы