想象一下,我在一个窗口上有两个 WPF 按钮,内容如下:
<Button>OK</Button>
<Button>Cancel</Button>
我希望这些按钮的宽度相同,但是在
Content
的情况下绑定(bind)到给定用户语言的本地化值,我不知道按钮需要多宽才能容纳新内容。我如何对这些按钮应用最小宽度,以便最宽的宽度(根据内容)被有效地用作
MinWidth
两者,从而使它们保持一致?或者换一种说法:我不希望按钮是它们容器的宽度(除非以一种聪明的方式使用容器是我问题的答案),我不希望它们每个都只是大小他们自己的内容,因为这将使他们不同的大小。我想要介于两者之间的东西。具有最大内容大小以显示其内容的内容,以及所有其他内容大小相同的宽度,因此宽度都相等。
我希望答案在于将它们放入某种容器中。我知道我可以使用
Grid
并让它们填充网格“单元格”,但重点是我也不希望它们太宽。我知道我可以有一些在 Content_Changed
上运行的代码隐藏。按钮的事件并将最小宽度设置为最宽按钮的最小宽度,但我对纯 xaml 方法感兴趣。我可能需要创建一个自定义控件来扩展 ItemsControl
当添加新项目或重新调整大小并将最宽项目的宽度应用为 MinWidth
时,该 rusn 代码隐藏的所有其他项目。提前谢谢了。
最佳答案
网格
<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
.
关于wpf - 根据最大按钮的内容均匀大小的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6249946/