这篇博客将介绍如何在 UWP 开发中使用 AdaptiveTrigger 实现自适应布局。
场景 1:窗体宽度大于 800 时,窗体背景色为绿色,窗体在 0 到 800 之间为蓝色。
XAML Code:
- <Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <VisualStateManager.VisualStateGroups>
- <VisualStateGroup x:Name="WindowStates">
- <!--Windows's size>= 800, background green-->
- <VisualState x:Name="WideState">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="800" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="LayoutRoot.Background" Value="Green" />
- </VisualState.Setters>
- </VisualState>
- <!--Windows's size>0 and < 800, background blue-->
- <VisualState x:Name="NarrowState">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="0" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="LayoutRoot.Background" Value="Blue" />
- </VisualState.Setters>
- </VisualState>
- </VisualStateGroup>
- </VisualStateManager.VisualStateGroups>
- </Grid>
在 VisualStateGroup 中有两组 VisualState 对 Grid 的背景色进行了设置。
场景 2:一个窗体上面有一个 TextBlock,TextBox,Button。当窗体宽度合适时,这三个控件水平排放;缩小窗体后,垂直排放。
XAML Code:
- <Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <RelativePanel HorizontalAlignment="Stretch">
- <TextBlock x:Name="MyTextBlock" Text="TextBlock" Margin="5,10" />
- <TextBox x:Name="MyTextBox" Text="TextBox" Width="200" Margin="5,10" />
- <Button x:Name="MyButton" Content="Button" Margin="5,10" Width="200" />
- </RelativePanel>
- <VisualStateManager.VisualStateGroups>
- <VisualStateGroup x:Name="WindowState">
- <VisualState x:Name="WideState">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="600" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="MyTextBox.(RelativePanel.RightOf)" Value="MyTextBlock"
- />
- <Setter Target="MyButton.(RelativePanel.RightOf)" Value="MyTextBox" />
- </VisualState.Setters>
- </VisualState>
- <VisualState x:Name="NarrowState">
- <VisualState.StateTriggers>
- <AdaptiveTrigger MinWindowWidth="0" />
- </VisualState.StateTriggers>
- <VisualState.Setters>
- <Setter Target="MyTextBox.(RelativePanel.Below)" Value="MyTextBlock" />
- <Setter Target="MyTextBox.(RelativePanel.AlignLeftWith)" Value="MyTextBlock"
- />
- <Setter Target="MyButton.(RelativePanel.Below)" Value="MyTextBox" />
- <Setter Target="MyButton.(RelativePanel.AlignLeftWith)" Value="MyTextBlock"
- />
- </VisualState.Setters>
- </VisualState>
- </VisualStateGroup>
- </VisualStateManager.VisualStateGroups>
- </Grid>
VisualState.Setter 的 Target 中 RalativePanel 的内容都用括号圈起来了是因为这些都是附加属性。这里同时引入了一个 UWP 支持的布局控件 RelativePanel,关于 RelativePanel 布局,
可以参考:https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.relativepanel.aspx
来源: http://www.cnblogs.com/yang-fei/p/6135893.html