根据最大按钮的内容,尺寸均匀的按钮

时间:2011-06-06 09:23:48

标签: wpf xaml layout

想象一下,我在窗口上有两个WPF按钮,内容如下:

<Button>OK</Button>
<Button>Cancel</Button>

我希望这些按钮具有相同的宽度,但是在Content绑定到给定用户语言的本地化值的情况下,我不知道按钮需要容纳多宽新内容。

如何对这些按钮应用最小宽度,以使最宽的宽度(根据内容)有效地用作两者的MinWidth,从而使它们保持一致?

或换句话说:我不希望按钮是他们容器的宽度(除非以巧妙的方式使用容器是我的问题的答案),我不希望他们每个人都只是尺寸与他们自己的内容,因为这将使他们不同的大小。我想要介于两者之间。具有最大尺寸内容的显示内容,以及所有其他尺寸相同的宽度,因此宽度都相等。

我希望答案在于将它们放在某种容器中。我知道我可以使用Grid并让它们填充网格“单元格”,但重点是我不希望它们宽。我知道我可以在按钮的Content_Changed事件上运行一些代码隐藏,并将最小宽度设置为最宽按钮,但我对纯xaml方法感兴趣。我可能需要创建一个自定义控件,扩展ItemsControl,当添加或重新调整新项目时,rusn代码隐藏,并将最宽项目的宽度应用为所有其他项目的MinWidth

非常感谢提前。

3 个答案:

答案 0 :(得分:22)

网格

  <Grid HorizontalAlignment="Right" Grid.IsSharedSizeScope="true">
    <Grid.ColumnDefinitions>
        <ColumnDefinition SharedSizeGroup="A"/>
        <ColumnDefinition SharedSizeGroup="A"/>
    </Grid.ColumnDefinitions>
    <Grid.Children>
        <Button Grid.Column="0" Content="OK"/>
        <Button Grid.Column="1" Content="Cancel"/>
    </Grid.Children>
  </Grid>

这可以分解,你只需要在共同的祖先上设置IsSharedSizeScope,例如:

    <StackPanel Grid.IsSharedSizeScope="true">
        <Grid HorizontalAlignment="Right">
            <Grid.ColumnDefinitions>
                <ColumnDefinition SharedSizeGroup="A"/>
            </Grid.ColumnDefinitions>
            <Grid.Children>
                <Button Grid.Column="0" Content="OK"/>
            </Grid.Children>
        </Grid>
        <!-- ... -->
        <Grid HorizontalAlignment="Left">
            <Grid.ColumnDefinitions>
                <ColumnDefinition SharedSizeGroup="A"/>
            </Grid.ColumnDefinitions>
            <Grid.Children>
                <Button Grid.Column="0" Content="Cancel"/>
            </Grid.Children>
        </Grid>
    </StackPanel>

为防止按钮变得过大,请将网格的HorizontalAlignment更改为Stretch以外的其他设置或设置MaxWidth

答案 1 :(得分:13)

Use UniformGrid

<UniformGrid HorizontalAlignment="Right" Rows="1" Columns="2">
  <Button Content="Ok" Grid.Column="0"/>
  <Button Content="Cancel" Grid.Column="1"/>
</UniformGrid>

答案 2 :(得分:0)

我喜欢在这种情况下使用包装面板。加载后,我使用linq从所有子级获得最大宽度。 (假设孩子都是按钮)

xaml

<WrapPanel Name="WP_ButtonSelections" Orientation="Horizontal" HorizontalAlignment="Center" Loaded="WP_ButtonSelections_Loaded"></WrapPanel>

cs

WP_ButtonSelections.Children.Add(new Button() { Content = "Hello" });
WP_ButtonSelections.Children.Add(new Button() { Content = "Hello World" });


private void WP_ButtonSelections_Loaded(object sender, RoutedEventArgs e)
{
   double maxWidth = WP_ButtonSelections.Children.OfType<FrameworkElement>().Max(elm => elm.ActualWidth);
   WP_ButtonSelections.Children.OfType<FrameworkElement>().ToList().ForEach(elm => elm.Width = maxWidth);
}

我需要一个编程解决方案。这需要加载事件,因为以编程方式添加的按钮在调用ActualWidth时不会定义WP_ButtonSelections.Children.Add()。此解决方案应该与xaml定义的按钮或xaml和程序化按钮的混合使用。