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

Nei*_*ell 29 wpf layout xaml

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

<Button>OK</Button>
<Button>Cancel</Button>
Run Code Online (Sandbox Code Playgroud)

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

我如何将最小宽度应用于这些按钮,使得最宽的宽度(根据内容)有效地用作MinWidth两者的宽度,从而保持它们的均匀性?

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

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

提前谢谢了.

H.B*_*.B. 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>
Run Code Online (Sandbox Code Playgroud)

这可以分解,你只需要设置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>
Run Code Online (Sandbox Code Playgroud)

为了防止按钮变得太大HorizontalAlignment,将网格更改为除了Stretch或设置之外的其他内容MaxWidth.


Ami*_*ito 14

Use UniformGrid

<UniformGrid HorizontalAlignment="Right" Rows="1" Columns="2">
  <Button Content="Ok" Grid.Column="0"/>
  <Button Content="Cancel" Grid.Column="1"/>
</UniformGrid>
Run Code Online (Sandbox Code Playgroud)

  • 这个答案的优点是允许您为不需要的按钮设置Visibility ="Collapsed",整个单元格消失 - 使用SharedSizeGroup网格执行此操作会留下一个洞,这可能不是您想要的.再加上它的笨蛋! (2认同)
  • “ Grid.Column”和“ Grid.Row”被“ UniformGrid”忽略,控件按Xaml中的声明顺序添加。 (2认同)