WPF Wrappanel 中的浮动效果

3
我不知道如何在改变窗口大小时进行所需的操作。
为了更好地解释,我画了一张图,您可以看到我的程序在小窗口(#1)下的表现以及最大化(#2)后的表现。
我想问一下是否可能(以及如何实现)让它像#3一样在最大化时表现出来——添加水平间隔器,将我的WrapPanel向左移动并将Grid向右移动。
我在XAML中有以下代码:
<Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <!-- In this example row 0 and 2 have no data -->

        <WrapPanel Name="TopMenu" Width="auto" HorizontalAlignment="Center" Grid.Row="1"> 
            <WrapPanel HorizontalAlignment="Center" Height="160" Margin="10,10,0,0">
                content 1
            </WrapPanel>        

            <Grid x:Name="InfoTable" MinWidth="600" Margin="20,20,20,0">
                content 2
            </Grid>
        </WrapPanel>
</Grid>

感谢Blažek
1个回答

3
您要寻找的内容并没有现成的解决方案。您需要手动设置控件以填充宽度,否则wrappanel只会从左到右布局,并且所有内容都向左对齐。但是下面有一些代码供您参考,可以帮助您朝着正确的方向前进。
<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication4"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:WidthConverter x:Key="WidthConverter" />
    </Window.Resources>
    <WrapPanel>
        <Button Content="Button1" Width="150"  Height="20"    />
        <TextBlock Width="{Binding Converter={StaticResource WidthConverter}, Path=ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Text=" "/>
        <Button Content="Button2" Width="150"  Height="20"   />
    </WrapPanel>
</Window>

您需要填充空间的转换器如下所示:

namespace WpfApplication4 {
    public class WidthConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            Console.WriteLine(value.GetType());
            var w = (double)value;
            return w - 350;
        }

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

需要注意的是,我们已经硬编码了数字(350),这个值比行上所有控件的宽度都要大。因此每个按钮150像素,加上控件周围的一些填充。如果行上还有其他控件,那么问题会变得更加复杂,但您可以添加另一个转换器来计算它们的宽度。


非常感谢,我之前以为没有原生支持这个功能,有点遗憾... - jreh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接