【问题标题】:WPF float like behaviour in wrappanel包装面板中的 WPF 浮动行为
【发布时间】:2014-04-11 12:27:17
【问题描述】:

我不知道如何在更改窗口大小时做应得的事情

为了更好地解释,我绘制了图片,您可以在其中看到我的程序在小窗口 (#1) 下的行为以及最大化时的行为 (#2)。

我想尽可能(以及如何?)使其在最大化时表现得像#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>

感谢布拉泽克

【问题讨论】:

    标签: c# wpf wrappanel


    【解决方案1】:

    您正在寻找的东西并不是开箱即用的。您必须手动设置一个控件来填充宽度,否则,包裹面板只是从左到右布置,所有内容都向左对齐。但是这里有一些代码可以让你朝着正确的方向前进。

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

    【讨论】:

    • 非常感谢,我还以为没有原生支持呢,可惜了……
    猜你喜欢
    • 2011-01-08
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多