WPF响应式设计(液体布局)

时间:2018-07-29 08:43:54

标签: c# wpf xaml layout responsive-design

我想使我的WPF应用程序成为完全响应的应用程序,我读了很多关于该主题的帖子,但是不幸的是,所有这些帖子并没有帮助我完成我想要的事情。

我想要做的是使我的应用程序像网站一样响应..这意味着如果我必须垂直排列按钮,并且我将页面宽度最小化,那么这两个按钮应水平排列。像这样:

  

普通窗口

enter image description here

  

调整大小后

enter image description here

在WPF中可以吗?我要做的是 This问题中提到的“液体布局”吗?

1 个答案:

答案 0 :(得分:3)

是的,一种实现方法是使用WrapPanel和一个hacky转换器以确保中间元素占用所有剩余空间:

<Window.Resources>
    <local:WpConverter x:Key="WpConverter"/>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Rectangle Grid.Row="0" Fill="BlueViolet" Height="75" HorizontalAlignment="Stretch"/>
    <WrapPanel x:Name="wp" Grid.Row="1" HorizontalAlignment="Stretch" Orientation="Horizontal">
        <StackPanel Width="100">
            <Rectangle Fill="CornflowerBlue" Height="20" Margin="3"/>
            <Rectangle Fill="CornflowerBlue" Height="20" Margin="3"/>
            <Rectangle Fill="CornflowerBlue" Height="20" Margin="3"/>
            <Rectangle Fill="CornflowerBlue" Height="20" Margin="3"/>
        </StackPanel>
        <Grid HorizontalAlignment="Stretch" Width="{Binding Path=ActualWidth, ElementName=wp,Converter={StaticResource WpConverter}}"></Grid>
        <Rectangle Margin="3" Fill="CornflowerBlue" Width="94" Height="200" ></Rectangle>
    </WrapPanel>
    <Rectangle Margin="3" Grid.Row="2" Fill="Cyan" Height="50" HorizontalAlignment="Stretch"/>

</Grid>

转换器的作用是确保中间网格条带占据所有剩余空间(格子宽度-左侧边栏宽度-右侧边栏宽度):

   public class WpConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Int32.Parse(value.ToString()) - 200;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Ps:您也可以使用多值转换器并传递左右侧边栏的ActualWidths,而不是在转换器中硬编码它们的值。

结果:

enter image description here