2014-05-06 27 views
0

所以我試圖讓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; 
} 
+0

有一種更好的方式(因爲它的作品更好,要簡單得多)的方法比我的「調整」,以在這裏找到:http://stackoverflow.com/a/23517858/1662314 – Andreas

回答

1

聽起來像你需要一個StretchPanel。 Silverlight沒有這樣的面板,但你可以自己寫。 我通過google StretchPanel blog發現了一個,只是快速瀏覽了一下代碼,它對我來說看起來還不錯。

<ItemsControl.ItemsPanel> 
    <ItemsPanelTemplate> 
     <StretchPanel Orientation="Horizontal"/> 
    </ItemsPanelTemplate> 
</ItemsControl.ItemsPanel> 
+0

我需要什麼,幾乎,我對MeasureOverride和ArrangeOverride方法進行了一些調整,所以所有的東西都被拉伸到各處。感謝您提供該博客條目。將這些方法添加到主帖子中。 – Andreas

+0

請注意,如果放置在StackPanel中,調整後的方法將導致運行時錯誤,因爲如果放置在StackPanel中,則可用大小將爲Height = Infinity,Width = Infinity。 – Andreas

1

我認爲這是你的StackPanel使用是導致缺乏彈力。如果用不同類型的控件替換面板模板,它將遵循HorizontalAlignment="Stretch"請求。