使用相同宽度的元素填充ItemsComtrol中的所有可用空间

时间:2017-10-19 13:50:42

标签: wpf xaml

我有一个ItemsControl,ItemsPanel是由DockPanel制作的。

在DockPanel内部,我可以有一个,两个或三个按钮。问题来自按钮的宽度:我希望三个元素具有相同的大小,但元素采用他们需要的大小(最后一个元素占用多余的宽度,因为LastChildFill为真)。

我可以手动为按钮提供相同的宽度吗?

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

1 个答案:

答案 0 :(得分:3)

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