我是WPF新手并致力于动态视图创建。我有一个场景,我需要根据监视器格局和/或肖像修改我的UI,如
我已经拥有告诉我监视器处于横向或纵向模式的属性。
这可以在WPF中使用吗?
答案 0 :(得分:3)
这是可能的。您将使用DataTrigger创建一个实现布局和在它们之间切换的视图:
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Content">
<Setter.Value>
<!-- Put your portrait layout here -->
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsLandscape}" Value="True">
<Setter Property="Content">
<Setter.Value>
<!-- Put your landscape layout here -->
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
使用{Binding IsLandscape}表达式,DataTrigger会观察视图的DataContext的IsLandscape属性。 This is explained in detail on MSDN。这意味着您应该将视图的DataContext属性设置为具有您在问题中提到的IsLandscape属性的对象。完整的例子:
创建新的空WPF项目。
更新MainWindow.xaml.cs
:
public MainWindow()
{
this.InitializeComponent();
this.DataContext = this; // You would put a ViewModel here when using MVVM design pattern
}
public static readonly DependencyProperty IsLandscapeProperty
= DependencyProperty.Register("IsLandscape",
typeof (bool),
typeof (MainWindow));
public bool IsLandscape
{
get { return (bool) GetValue(IsLandscapeProperty); }
set { SetValue(IsLandscapeProperty, value); }
}
private void ChangeOrientation(object sender, RoutedEventArgs e)
{
this.IsLandscape = !this.IsLandscape;
}
更新MainWindow.xaml
。删除默认网格并改为:
<Window.Resources>
<Style TargetType="UserControl">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Background" Value="#CCDDEE" />
<Setter Property="Margin" Value="3" />
</Style>
</Window.Resources>
<DockPanel>
<Button DockPanel.Dock="Bottom" Margin="5" Content="Change Orientation"
Click="ChangeOrientation" />
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Content">
<Setter.Value>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<UserControl Content="Sub 1" />
<UserControl Grid.Column="1" Content="Sub 2" />
<UserControl Grid.Row="1" Grid.ColumnSpan="2" Content="Main" />
</Grid>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding IsLandscape}" Value="True">
<Setter Property="Content">
<Setter.Value>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<UserControl Grid.Column="1" Content="Sub 1" />
<UserControl Grid.Column="1" Grid.Row="1" Content="Sub 2" />
<UserControl Grid.RowSpan="2" Content="Main" />
</Grid>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DockPanel>
答案 1 :(得分:1)
是的,您可以同时实现此UI并使用VisualStateManager来控制要显示的UI。
您还可以使用converter
将布局容器的可见性绑定到您的媒体资源