在ItemsComtrol中填充具有相同宽度元素的所有可用空间
问题描述:
我有一个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>
答
一个UniformGrid
与单行会做你想要什么:
<ItemsPanelTemplate x:Key="Panel1">
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
例子:
<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>