前言
刘铁猛老师UWP教程学习笔记
VisualStateManager
- VisualStateManager和它的小伙伴们
- VisualStateGroup一组与组之间的状态可以叠加使用
- VisualState-由Trigger或后台代码触发,使用动画或者Setter来改变控件的属性
- 使用技巧
- 尽可能避免在后台代码中操作VisualState
- 尽可能把UI逻辑与业务逻辑分开
- 示例
宽度等于700
大于700
<RelativePanel Padding="5">
<Rectangle
x:Name="rect"
Width="400"
Height="500"
Fill="Red" />
<Rectangle
x:Name="rect1"
Height="50"
Fill="Orange"
RelativePanel.AlignLeftWith="rect"
RelativePanel.AlignRightWith="rect"
RelativePanel.Below="rect" />
<Rectangle
Height="90"
Fill="Blue"
RelativePanel.AlignLeftWith="rect1"
RelativePanel.AlignRightWith="rect1"
RelativePanel.Below="rect1" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState>
<VisualState.Setters>
<!-- 附加属性加() -->
<Setter Target="rect1.(RelativePanel.AlignLeftWith)" Value="" />
<Setter Target="rect1.(RelativePanel.AlignRightWith)" Value="" />
<Setter Target="rect1.(RelativePanel.Below) " Value="" />
<Setter Target="rect1.(RelativePanel.RightOf)" Value="rect" />
<Setter Target="rect1.Width" Value="150" />
</VisualState.Setters>
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="700" />
</VisualState.StateTriggers>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</RelativePanel>
自定义VisualStateManager
1.继承StateTriggerBase
public class MyTrigger : StateTriggerBase
{
public MyTrigger()
{
Window.Current.SizeChanged += (s, e) =>
{
if (e.Size.Width >= 700)
{
this.SetActive(true);
}
else
{
this.SetActive(false);
}
};
}
2.XAML中使用
<RelativePanel Padding="5">
<Rectangle
x:Name="rect"
Width="400"
Height="500"
Fill="Red" />
<Rectangle
x:Name="rect1"
Height="50"
Fill="Orange"
RelativePanel.AlignLeftWith="rect"
RelativePanel.AlignRightWith="rect"
RelativePanel.Below="rect" />
<Rectangle
Height="90"
Fill="Blue"
RelativePanel.AlignLeftWith="rect1"
RelativePanel.AlignRightWith="rect1"
RelativePanel.Below="rect1" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState>
<VisualState.Setters>
<!-- 附加属性加() -->
<Setter Target="rect1.(RelativePanel.AlignLeftWith)" Value="" />
<Setter Target="rect1.(RelativePanel.AlignRightWith)" Value="" />
<Setter Target="rect1.(RelativePanel.Below) " Value="" />
<Setter Target="rect1.(RelativePanel.RightOf)" Value="rect" />
<Setter Target="rect1.Width" Value="150" />
</VisualState.Setters>
<VisualState.StateTriggers>
<!--<AdaptiveTrigger MinWindowWidth="700" />-->
<local:MyTrigger/>
</VisualState.StateTriggers>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</RelativePanel>