2010-07-01 73 views
11

我在網上找到了關於在WPF中繪製虛線的幾篇文章。但是,他們似乎圍繞使用WPF中的UIElement的Line-class。它是這樣的:在WPF裝飾器中畫虛線

Line myLine = new Line(); 
DoubleCollection dashes = new DoubleCollection(); 
dashes.Add(2); 
dashes.Add(2); 
myLine.StrokeDashArray = dashes; 

現在,我在一個裝飾,我只能訪問繪圖上下文。在那裏,我或多或少降低到圖元,畫筆,鋼筆,幾何等,這看起來更像是:

var pen = new Pen(new SolidColorBrush(Color.FromRgb(200, 10, 20)), 2); 
drawingContext.DrawLine(pen, point1, point2); 

我卡住怎麼辦虛線上這個級別的API。我希望這不是「一條一條地劃小線」,而是我還沒見過的其他東西......

回答

22

看看Pen.DashStyle屬性。您可以使用DashStyles類的成員給出一些預定義的破折號樣式,或者您可以通過創建新的DashStyle實例來指定自己的破折號和間隙模式。

var pen = new Pen(new SolidColorBrush(Color.FromRgb(200, 10, 20)), 2); 
pen.DashStyle = DashStyles.Dash; 
drawingContext.DrawLine(pen, point1, point2); 
+1

Doh,就是這樣,不知何故,我錯過了那個屬性。現在在德國是35 +°C :) – flq 2010-07-01 12:36:56

1

你並沒有被卡在基元中。如果你遵循這種模式,你可以添加任何東西到裝飾者。

public class ContainerAdorner : Adorner 
{ 
    // To store and manage the adorner's visual children. 
    VisualCollection visualChildren; 

    // Override the VisualChildrenCount and GetVisualChild properties to interface with 
    // the adorner's visual collection. 
    protected override int VisualChildrenCount { get { return visualChildren.Count; } } 
    protected override Visual GetVisualChild(int index) { return visualChildren[index]; } 

    // Initialize the ResizingAdorner. 
    public ContainerAdorner (UIElement adornedElement) 
     : base(adornedElement) 
    { 
     visualChildren = new VisualCollection(this); 
     visualChildren.Add(_Container); 
    } 
    ContainerClass _Container= new ContainerClass(); 

    protected override Size ArrangeOverride(Size finalSize) 
    { 
     // desiredWidth and desiredHeight are the width and height of the element that's being adorned. 
     // These will be used to place the Adorner at the corners of the adorned element. 
     double desiredWidth = AdornedElement.DesiredSize.Width; 
     double desiredHeight = AdornedElement.DesiredSize.Height; 

     FrameworkElement fe; 
     if ((fe = AdornedElement as FrameworkElement) != null) 
     { 
      desiredWidth = fe.ActualWidth; 
      desiredHeight = fe.ActualHeight; 
     } 

     _Container.Arrange(new Rect(0, 0, desiredWidth, desiredHeight)); 

     return finalSize; 
    } 
}