2014-02-24 26 views
0

它返回一個幾何體,但這是一個抽象類。 我正在創建一個文本形狀,並且想要緩存這個幾何體。
BuildGeometry可能會返回不同類型,感覺可疑,因此我可能做錯了什麼。我可以破解代碼(它會在運行後立即執行),但我怎樣才能確定它始終是同一類型的?FormattedText.BuildGeometry返回哪個幾何?

public class Label : ShapeBase 
    { 
     RectangleGeometry geometry = new RectangleGeometry(); 

     protected override Geometry DefiningGeometry 
     { 
      get { return geometry; } 
     } 

     protected override Size MeasureOverride(Size constraint) 
     { 
      return constraint; 
     } 

     public string Text 
     { 
      get { return (string)GetValue(TextProperty); } 
      set { SetValue(TextProperty, value); } 
     } 

     public static readonly DependencyProperty TextProperty = 
      DependencyProperty.Register("Text", typeof(string), typeof(Label), new UIPropertyMetadata(string.Empty, OnTextChanged)); 

     private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
      Label label = (Label)d; 
      label.SetGeometry(label.Text); 
      label.InvalidateVisual(); 
     } 

     private void SetGeometry(string text) 
     { 
      FormattedText formattedtext = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Tahoma"), 16, Brushes.Black); 
      GeometryGroup group = (GeometryGroup)formattedtext.BuildGeometry(new Point(0, 0)); 
     } 
    } 
+1

你能告訴我們創建文本形狀的代碼嗎?另外:你可以設置一個斷點並檢查類型。 –

+0

@ErnodeWeerd看我的編輯。 – Gerard

回答

2

如果您在formattedtext.BuildGeometry設置斷點並檢查返回值,你就會意識到,這是一個GeometryGroup

var geometry = formattedText.BuildGeometry(new Point()); 
var geometryGroup = geometry as GeometryGroup; 

if (geometryGroup != null) 
{ 
    foreach (var childGeometry in geometryGroup.Children) 
    { 
     // do something with the child geometries... 
    } 
} 

當我用一個簡單的FormattedText測試這一點,子女頂級GeometryGroup本身就是GeometryGroups,其PathGeometries作爲子級。我的假設是,二級GeometryGroups每個包含一個FormattedText對象的文本行,而PathGeometries包含單個字符或字形。

0

從您的代碼看起來像RectangleGeometry

RectangleGeometry geometry = new RectangleGeometry(); 

    protected override Geometry DefiningGeometry 
    { 
     get { return geometry; } 
    }