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

Abd*_*rif 5 c# wpf layout xaml responsive-design

我想使WPF应用程序成为完全响应的应用程序,我读了很多关于该主题的文章,但是不幸的是,所有这些文章都没有帮助我完成我想要的工作。

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

普通窗口

在此处输入图片说明

调整大小后

在此处输入图片说明

在WPF中有可能吗?我要做的是 这个问题中提到的“液体布局”吗?

Sam*_*Dev 6

是的,一种实现方法是使用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>
Run Code Online (Sandbox Code Playgroud)

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

   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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

结果:

在此处输入图片说明