在 WPF 中同时支持横向和纵向视图

  • 本文关键字:视图 横向 支持 WPF c# wpf
  • 更新时间 :
  • 英文 :


我是 WPF 的新手,无法找到支持横向和纵向视图的最佳方法。我有哪些选择?

纵向视图的控件位置将与横向视图完全不同。

如果我没有错过某些东西,你的意思是移动视图",只需在ViewModel上添加一个新的bool变量(类似于isLandscape)来控制将使用哪个DataTemplate。您可以使用触发器或任何其他方式控制它。

我想这个问题需要更多的标签。

通用Windows平台有一个AdaptiveTrigger,允许您指定在哪些条件下设置给定VisualState。然后,使用样式设置器,您可以更改页面的布局以满足您的需求。

WPF 没有此功能,但您当然可以使用带有StoryboardsSizeChanged事件的VisualStateManager非常接近地模拟它。

对于窗口内容的根元素,您可以添加包含两组的VisualStateManager

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ApplicationViewStates">
<VisualState x:Name="Landscape"/>
<VisualState x:Name="Portrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames  
Storyboard.TargetProperty="SomeProperty" 
Storyboard.TargetName="SomeElement">
<DiscreteObjectKeyFrame KeyTime="0" Value="SomeValue"/>
</ObjectAnimationUsingKeyFrames>
...
</Storyboard>
</VisualState>

现在,在代码隐藏中,您可以连接WindowSizeChanged事件:

this.SizeChanged += (s,e) =>
{
//some condition you want to use to distinguish landscape and portrait
if ( Width < Height )
{
VisualStateManager.GoToState(this, "Portrait", false);
}
else
{
VisualStateManager.GoToState(this, "Landscape", false);
}
}

或者,您可以使用SizeChangedevent 在代码中执行所有操作,但在这种情况下,如果您有多个状态,则需要首先将每个属性重置为其默认值:

this.SizeChanged += (s,e) =>
{
//reset all changed properties to default value here
...
//some condition you want to use to distinguish landscape and portrait
if ( Width < Height )
{
//set properties for portrait
}
}

最新更新