所以我試圖讓itemcontrol中的一些物品水平拉伸,當你看看下面的代碼時,你可能會注意到我非常絕望。我簡化了我的代碼並添加了一些顏色,以便更好地瞭解哪些控件開始和結束的位置......是否有可能告訴項目同樣拉伸並填充整個水平空間?如何在itemcontrol中strech物品
<Grid Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ItemsControl x:Name="HorizontalListBox" Background="Blue"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
<ItemsControl.Items>
<System:Int32>4</System:Int32>
<System:Int32>4</System:Int32>
<System:Int32>4</System:Int32>
<System:Int32>4</System:Int32>
<System:Int32>4</System:Int32>
</ItemsControl.Items>
<ItemsControl.Template>
<ControlTemplate>
<ItemsPresenter HorizontalAlignment="Stretch"/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="Green"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<TextBlock Text="Test" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
是這樣的:this http://image-upload.de/image/0TgZx9/0dd27b5326.png
我不過希望可能有綠色物品舒展所有的地方。
編輯:謝謝你在回答中發現它下面有一些調整工作的博文:
protected override Size MeasureOverride(Size availableSize)
{
var size = new Size();
SetSide(ref size, GetSide(availableSize));
foreach (UIElement child in Children)
{
child.Measure(availableSize);
SetOtherSide(ref size, Math.Max(GetOtherSide(size), GetOtherSide(child.DesiredSize)));
}
_measureSize = size;
return size;
}
protected override Size ArrangeOverride(Size finalSize)
{
double offset = 0;
foreach (UIElement child in Children)
{
double side = GetSide(_measureSize)/Children.Count;
var final = new Size();
SetSide(ref final, side);
SetOtherSide(ref final, GetOtherSide(finalSize));
child.Arrange(new Rect(GetOffsetPoint(offset), final));
offset += side;
}
return finalSize;
}
有一種更好的方式(因爲它的作品更好,要簡單得多)的方法比我的「調整」,以在這裏找到:http://stackoverflow.com/a/23517858/1662314 – Andreas