2009-08-26 76 views
6

我需要在Border控件(或類似的)內繪製一些簡單的線條,這些線條總是伸展到邊框的邊界。有沒有辦法只拉伸線條而不是它的筆?不涉及大量的C#?WPF繪圖延伸而不伸展筆

在這個版本的線條舒展:

<Border> 
    <Border.Background> 
     <DrawingBrush> 
     <DrawingBrush.Drawing> 
      <DrawingGroup> 
       <GeometryDrawing Brush="Red"> 
        <GeometryDrawing.Geometry> 
        <GeometryGroup> 
         <RectangleGeometry Rect="0,0 100,1000" /> 
         <LineGeometry StartPoint="0,0" EndPoint="100,1000"/> 
         <LineGeometry StartPoint="100,0" EndPoint="0,1000"/> 
        </GeometryGroup> 
        </GeometryDrawing.Geometry> 
        <GeometryDrawing.Pen> 
        <Pen Thickness="20" Brush="Black"/> 
        </GeometryDrawing.Pen> 
       </GeometryDrawing> 
      </DrawingGroup> 
     </DrawingBrush.Drawing> 
     </DrawingBrush> 
    </Border.Background> 
</Border> 

我想出了最好的解決辦法是這樣的:

<Border> 
    <Grid> 
     <Path Stretch="Fill" Fill="Red" Stroke="Black" StrokeThickness="4" Data="M0,0 L100,0 100,1000 0,1000 z" /> 
     <Path Stretch="Fill" Stroke="Black" StrokeThickness="4" Data="M 0,0 L0,0 100,1000" /> 
     <Path Stretch="Fill" Stroke="Black" StrokeThickness="4" Data="M 100,0 L100,0 0,1000" /> 
    </Grid> 
</Border> 

但是是不是有更好的解決辦法?那不涉及額外的網格?

回答

5

我已經做到了這一點。

  1. 放置一個路徑在畫布中。
  2. 將path.Data設置爲表示您的數據的幾何爲邏輯範圍的百分比。
  3. 將path.Data.Transform設置爲一個ScaleTransform,並將ScaleX和ScaleY綁定到實際的寬度和高度。
+1

真正整潔的提示!我節省了幾個小時的挫折或轉換器負載。 – 2012-04-10 18:50:12

1

沒有我所知道的。但是,除非你正在做的事情真的很奢侈,它真的不是一個很大的努力來覆蓋OnRender和自己繪製它:

public class CustomBorder : Border 
{ 
    protected override void OnRender(DrawingContext dc) 
    { 
     base.OnRender(dc); 

     dc.DrawLine(new Pen(BorderBrush, BorderThickness.Top), new Point(0, 0), new Point(ActualWidth, ActualHeight)); 
    } 
} 

結果:

enter image description here

+1

我很詫異我不得不爲自己的控制做這麼簡單的事情。 – bitbonk 2009-08-26 21:56:29

4

在一條線,你可以將寬度(或高度,取決於您繪製線的方式)綁定到父容器的寬度以實現所需。

<Grid x:Name="Grid" Margin="10"> 
     <Border BorderBrush="Black" BorderThickness="1" /> 
     <Line X1="0" X2="{Binding ElementName=Grid, Path=ActualWidth}" Y1="1" Y2="1" Stroke="Red" Margin="0,10,0,0" /> 
     <Line X1="0" X2="{Binding ElementName=Grid, Path=ActualWidth}" Y1="1" Y2="1" Stroke="Green" Margin="0,30,0,0" /> 
     <Line X1="0" X2="{Binding ElementName=Grid, Path=ActualWidth}" Y1="1" Y2="1" Stroke="Blue" Margin="0,50,0,0" /> 
    </Grid> 

編輯:這是不使用另一種方式縮放路徑的數據,而不是可視組件結合

<Border BorderBrush="Black" BorderThickness="1" > 
    <Path Stroke="Red" StrokeThickness="1" Data="M0,0 1,0Z" Stretch="Fill" /> 
</Border> 
+0

你有沒有在VS 2008中嘗試過這個(我認爲是混合)?設計師將無休止地調整這種控制。它變得越來越大。這是因爲與父母的ActualWidth綁定的行比ActualWith稍長(認爲LineCap等)。這將導致acutal with被再次增加,這將導致線路端點被更新,等等。 – bitbonk 2009-08-26 21:55:27

+0

我的VS2008設計師看起來很好。當我運行它也看起來很好。 – mdm20 2009-08-26 22:01:51

+0

它似乎只發生,如果省略網格,並將其直接放在用戶控件中。 – bitbonk 2009-08-27 07:22:35