2011-06-06 89 views
25

想象我有一个窗口上的两个WPF按钮,与内容如下:大小均匀的按键根据大按钮的内容

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

我想这些按钮是相同的宽度,但是在这样一个场景, Content绑定到给定用户的语言的本地化值,我不知道按钮需要多大以适应新的内容。

我应该如何将最小宽度应用到这些按钮上,以使最宽宽度(根据内容)的宽度有效地用作两者的MinWidth,从而使它们保持均匀?或者换句话说:我不希望按钮是它们容器的宽度(除非以聪明的方式使用容器是我的问题的答案),我不希望它们每个只根据他们自己的内容进行尺寸调整,因为这会使他们的尺寸不同。我想要中间的东西。要显示内容的尺寸最大的尺寸,以及所有其他尺寸都要调整到相同宽度的尺寸,宽度都是相同的。

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

非常感谢提前。

+0

所以你说你不想使用并设置Buttons Width =“Auto”? – Willem 2011-06-06 09:45:52

+0

我不希望按钮是他们的容器的宽度(除非以聪明的方式使用容器是我的问题的答案),并且我不希望他们调整他们的内容的大小,因为这会使他们不同大小。我想要中间的东西。具有最大尺寸的内容以显示其内容,并且所有其他尺寸的尺寸都相同,因此宽度均相等。 – 2011-06-06 09:59:28

+0

那么我猜你的按钮都是分散在你的视图上,因为如果没有,并且它们都被分组了,那么ColumnDefinition就可以实现。如果他们都分散,我也想知道你的问题的一个很好的解决方案。 =) – Willem 2011-06-06 10:10:39

回答

7
Use UniformGrid 

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

这个答案的优点是允许你为不需要的按钮设置Visibility =“Collapsed”,并且整个单元消失 - 用SharedSizeGroup网格这样做会留下一个洞,这可能不是你想要的。 加上其terser! – Wolfshead 2016-06-24 07:25:20

18

网格

<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> 

为了防止按钮从becomming太大将网格的HorizontalAlignment更改为Stretch以外的值或设置MaxWidth