WPF像wrappanel中的行为一样浮动

时间:2014-04-11 12:27:17

标签: c# wpf wrappanel

我无法弄清楚在改变窗口大小时如何做到应得的东西

为了更好地解释,我画了一张图片,你可以看到我的程序在小窗口(#1)中的行为以及最大化时的方式(#2)。

enter image description here

我希望似乎有可能(以及如何?)使其在最大化时表现得像#3 - 添加水平间隔物,使我的包裹物向左和向右移动

我在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 个答案:

答案 0 :(得分: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个,另外一些用于控件周围的填充。一旦行上有其他控件,它将变得更加困难,但您也可以添加另一个转换器来计算它们的宽度。