2017-10-19 67 views
0

我有一個ItemsControl,ItemsPanel由DockPanel構成。在ItemsComtrol中填充具有相同寬度元素的所有可用空間

在DockPanel裏面,我可以有一個,兩個或三個按鈕。問題出在按鈕的寬度上:我想要三個具有相同大小的元素,但元素需要它們需要的大小(最後一個元素因爲LastChildFill爲true而佔用過多寬度)。

我可以給這些按鈕設置相同的寬度而無需手動提供它們的大小嗎?

<ItemsControl ItemTemplate="{StaticResource Template1}" ItemsSource="{Binding Path=options, Mode=OneWay}" ItemsPanel="{StaticResource Panel1}" HorizontalContentAlignment="Stretch"/> 

    <ItemsPanelTemplate x:Key="Panel1"> 
     <DockPanel Height="Auto" Width="Auto" LastChildFill="True"/> 
    </ItemsPanelTemplate> 

    <DataTemplate x:Key="BasicasTemplateOpciones" DataType="{x:Type local:MyOption}"> 
     <Grid HorizontalAlignment="Stretch"> 
      <Button DataContext="{Binding}" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" > 
       <Button.Template> 
        <ControlTemplate TargetType="{x:Type Button}"> 
         <Grid HorizontalAlignment="Stretch" VerticalAlignment="Center"> 
           <StackPanel Orientation="Horizontal"> 
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Stretch"/> 
            <TextBlock HorizontalAlignment="Right" VerticalAlignment="Stretch"/> 
           </StackPanel> 
          </Grid> 
        </ControlTemplate> 
       </Button.Template> 
      </Button> 
     </Grid> 
    </DataTemplate> 

回答

2

一個UniformGrid與單行會做你想要什麼:

<ItemsPanelTemplate x:Key="Panel1"> 
    <UniformGrid Rows="1" /> 
</ItemsPanelTemplate> 

例子:

enter image description here

<StackPanel Orientation="Vertical"> 
    <StackPanel.Resources> 
     <ItemsPanelTemplate x:Key="Panel1"> 
      <UniformGrid Rows="1" /> 
     </ItemsPanelTemplate> 
     <Style TargetType="ItemsControl" x:Key="ICStyle"> 
      <Style.Resources> 
       <Style TargetType="Button"> 
        <Setter Property="Margin" Value="2" /> 
       </Style> 
      </Style.Resources> 
      <Setter Property="ItemsPanel" Value="{StaticResource Panel1}" /> 
     </Style> 
    </StackPanel.Resources> 

    <ItemsControl Style="{StaticResource ICStyle}"> 
     <Button>Foo</Button> 
    </ItemsControl> 

    <ItemsControl Style="{StaticResource ICStyle}"> 
     <Button>Foo</Button> 
     <Button>Bar</Button> 
    </ItemsControl> 

    <ItemsControl Style="{StaticResource ICStyle}"> 
     <Button>Foo</Button> 
     <Button>Bar</Button> 
     <Button>Baz</Button> 
    </ItemsControl> 
</StackPanel> 
相關問題