2017-01-10 12 views
0

私は同じ高さのパネルにたくさんのアイテムを持っています。私はパネル内のアイテムがパネル自体の最大幅に基づいて幅を縮小したいと思っています。カスタムパネルの子要素を特定のサイズに強制するにはどうすればよいですか?

例 - パネルの幅が400の場合、パネルに4つのアイテムがあり、各アイテムの幅は100になります。2アイテムだった場合、各アイテムの幅は200になります。

child.Measureを2回目に呼び出すと、アイテムの予想幅でchild.DesiredSizeが完全に変更されます。どのように私はそれを与えている幅を取るように項目を強制するのですか?

public class DynamicShrinkPanel : StackPanel 
{ 
    public DynamicShrinkPanel() 
    { 
    } 

    protected override Size MeasureOverride(Size constraint) 
    { 
     Size desiredSize = new Size(); 
     foreach (UIElement child in InternalChildren) 
     { 
      // First call to get the desired size. 
      child.Measure(constraint); 
      double properChildWidth = constraint.Width/InternalChildren.Count; 
      // Second call to set what I want, doesn't do what I expect 
      child.Measure(new Size(properChildWidth, child.DesiredSize.Height)); 
      desiredSize.Height = child.DesiredSize.Height; 
      desiredSize.Width += child.DesiredSize.Width; 
     } 

     return desiredSize; 
    } 
} 
+1

'UniformGrid'を' Rows = "1" '' – ASh

+0

と使用できるように聞こえます。このためにカスタムパネルを作成しないでください。代わりにUniformGridを使用します。 – Clemens

+0

UniformGridは、ネストされているコントロールの幅を自動的に占有しません。だから、私の場合、使用可能な幅が500であれば、どれくらいの数のアイテムを入れても、すべて500を使用します。統一されたグリッドはできるだけスペースを取らないようです。 – user99999991

答えて

0

私は、正確な大きさではなく、ArrangeOverride方法を計算するためにMeassureOverrideを使用していない、それを考え出しました。

protected override Size MeasureOverride(Size constraint) 
{ 
    Size desiredSize = new Size(); 
    foreach (UIElement child in InternalChildren) 
    { 
     child.Measure(constraint); 
     desiredSize.Height = child.DesiredSize.Height; 
     desiredSize.Width = constraint.Width; 
    } 

    return desiredSize; 
} 

protected override Size ArrangeOverride(Size arrangeSize) 
    { 
     double offset = 0; 
     double properWidth = arrangeSize.Width/InternalChildren.Count; 
     foreach (UIElement child in InternalChildren) 
     { 
      child.Arrange(new Rect(offset, 0, properWidth, arrangeSize.Height)); 
      offset += properWidth; 
     } 

     return arrangeSize; 
    } 
関連する問題