2016-06-09 63 views
0

不好意思問這一個,因爲我發現很多類似的問題,但不知何故已經爲他們工作的解決方案似乎並不適用於此......ActualWidth的/的ActualHeight

我有生成路徑的一些自定義控件(一些是靜態的,一些綁定到更新的值)。

我在單個itemcontrol上顯示這些(使用畫布作爲itemspaneltemplate),並且我需要獲取各個項目的Y位置。 XAML爲如下所示的項目中的一個:

<Style TargetType="{x:Type pg:GraphVertexBelt}"> 
<Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="{x:Type pg:GraphVertexBelt}"> 
      <Border Background="Transparent"> 
       <StackPanel> 
        <Canvas Width="225" Height="20"> 
         <Ellipse Height="10" Width="10" Canvas.Left="10"/> 
         <Ellipse Height="10" Width="10" Canvas.Left="220"/> 
         <Line X1="15" Y1="0.5" X2="225" Y2="0.5"/> 
        </Canvas> 
        <Label Content="{Binding Item.Tag.Title}" HorizontalAlignment="Center"/> 
       </StackPanel> 
      </Border> 
     </ControlTemplate> 
    </Setter> 
</Setter> 

時遇到的問題是,的ActualHeight/ActualWidth的總是顯示爲零。

我試着:

  • 施加控制內的恆定定義的寬度和高度在畫布(這是不方便的,因爲它需要手動調整的每個控制)
  • 使用委託給在渲染之後識別所述寬度:

     Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Render, new Action(() => 
        { 
         Console.Write(Items[0].Item.ActualWidth); 
        })); 
    

的原因我需要這樣做的是,控件中元素的寬度和高度實際上是動態的,我需要能夠在相對於實際控件位置的適當位置註釋圖表。

任何幫助將不勝感激!

乾杯。

編輯

也許我需要更清楚地解釋一下這個意圖是否有意義。我有一個可縮放的畫布,其中顯示了一組控件。每個控件都需要放在畫布中,我需要知道畫布上這些控件的高度和寬度。

在每個控件中有一系列路徑(按照示例代碼),這些路徑都相對於彼此定位,所以我在控件中嵌入了一個畫布。控制器還具有標籤,上下文菜單等

如果沒有解決這個另一種更清潔的方式,然後我所有的耳朵:)

+1

覆蓋帆布的「測量和排列」如何?我認爲,這是最直接的方法。 – tgpdyk

+0

@tgpdyk - 你的意思是測量/安排「GraphVertexBelt」?不確定畫布包裝是否會有所幫助,因爲它包含一組類似的控件。我將研究是否可以重寫單個控件的這些函數,並查看它們的外觀。 – Squanchy

+0

我的意思是你的ItemsPanelTemplate是一個自定義畫布。我會發佈一個答案。 – tgpdyk

回答

1

我建議創建自己的帆布和覆蓋措施和安排。

public class MyCanvas : Canvas 
{ 
    protected override Size MeasureOverride(Size constraint) 
    { 
     Size desiredSize = new Size(); 
     foreach (UIElement child in this.Children) 
     { 
      // This is your "control" 
      child.Measure(constraint); 
      // This is the size of the "control". 
      var myControlSize = child.DesiredSize; 
     } 
     return desiredSize; 
    } 

    protected override Size ArrangeOverride(Size arrangeSize) 
    { 
     // When this is called, you should know the DesiredSize of each control 
     // and you can decide where each control location relative to the canvas. 
     return arrangeSize; 
    } 
} 

然後使用MyCanvas作爲ItemsPanelTemplate。

WPF Layout

+0

啊!花了我一段時間來弄清楚你告訴我的是什麼,但是現在這變得非常有意義。應該幫助我清理一堆我正在做的其他廢話......謝謝! – Squanchy

相關問題