如何在UWP应用程序中以编程方式自适应屏幕?

时间:2016-09-01 05:47:49

标签: uwp

我正试图找到如何在UWP应用程序中以编程方式自适应屏幕,但我无法得到任何相关的想法,是否有类似的东西?

1 个答案:

答案 0 :(得分:2)

Adaptive Triggers are the best solution for layout changes based on app's size. For examples see: https://www.microsoft.com/en-gb/developers/articles/week03aug15/designing-with-adaptive-triggers-for-windows-10/ .

A simple example for two buttons:

<Grid>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="Narrow">
            </VisualState>
            <VisualState x:Name="Wide">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="600" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="TestButton2.Visibility" Value="Visible" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <StackPanel>
        <Button x:Name="TestButton" Content="Test button" />
        <Button x:Name="TestButton2" Content="Test button" Visibility="Collapsed" />
    </StackPanel>
</Grid>

Once the app is wider than 600 pixels, the second button will become visible.

Other approaches

You can change the layout of the page in reaction to size changes using the Page's SizeChanged event, which is fired each time the user resizes the page. This is not a clean approach however and you are much better suited using the built-in adaptive triggers for this.

//in the page's constructor wire-up the SizeChanged event
this.SizeChanged += MainPage_SizeChanged;       

private void MainPage_SizeChanged( object sender, SizeChangedEventArgs e )
{
   if ( e.NewSize.Width < 768 )
   {
      //some layout changes
   }
   else if (e.NewSize.Width < 1024)
   {
      //some layout changes
   }
   else
   {
      //etc.
   }
}

You can also manually switch the current VisualState for the page from code.

First define some VisualStates in XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CustomGroup">
            <VisualState x:Name="ShowButtonState" />
            <VisualState x:Name="HideButtonState">
                <VisualState.Setters>
                    <Setter Target="TestButton.Visibility" Value="Collapsed" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Button x:Name="TestButton" Content="Test button" />
</Grid>

And then switch the states in code:

if ( someCondition )
{
   VisualStateManager.GoToState( this, "HideButtonState", false );
}            
else
{
   VisualStateManager.GoToState( this, "ShowButtonState", false );
}