2015-05-05 17 views
0

我嘗試使用WPF創建自定義控件。我在網上發現了很多很好的
教程和建議,所以我開始寫一個非常簡單的例子,讓我的手髒,並得到一些練習。我發現問題偶然發生在
與自定義控件的主題沒有什麼關係。所以我將xaml代碼提取爲一個簡單的wpf表單。WPF/Xaml,LineGeomtry內部網格的垂直對齊無法正常工作

<Window x:Class="WpfVerticalAigmentTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="200" Width="200"> 
<Grid> 
    <Grid Height="40" Background="LightCyan" VerticalAlignment="Center"> 
     <Path Stroke="Red" 
       StrokeThickness="20" VerticalAlignment="Center" > 
      <Path.Data> 
       <LineGeometry StartPoint="0,0" EndPoint="100,0"></LineGeometry> 
      </Path.Data> 
     </Path> 
    </Grid> 
</Grid> 

我的期望是得到在網格和要求保護中風厚度的一半上從中心每一側爲中心的線。但是,由於鏈接的圖像顯示不同於我的期望。

"Resulting visualization"

所以它看起來像我錯過了一個關於線狀或linegeomtry細節。如何顯示如下圖所示的行?

"Expected result"

回答

0

你需要匹配PathWidthLineGeometryHeightWidthHeight並設置VerticalAlignment屬性Bottom

<Grid Height="20" Width="200" Background="LightCyan" VerticalAlignment="Center"> 
    <Path Stroke="Red" StrokeThickness="20" VerticalAlignment="Bottom"> 
     <Path.Data> 
      <LineGeometry StartPoint="0,0" EndPoint="200,0"></LineGeometry> 
     </Path.Data> 
    </Path> 
</Grid> 

enter image description here

0

問題這裏是出發點o f Path的XY座標從左上角開始,並且該筆畫在兩個方向上都展開,但這樣只會使路徑變得更大(我無法真正地告訴您爲什麼,但這似乎就是這樣發生的)。

你可以看到這個在設計視圖相當不錯:

http://i.imgur.com/3c1ZFaI.png

若要解決此只需移動y座標下的筆觸大小的一半。

<Grid Height="40" 
     VerticalAlignment="Center" 
     Background="LightCyan"> 
    <Path VerticalAlignment="Center" 
      Stroke="Red" 
      StrokeThickness="20"> 
     <Path.Data> 
      <LineGeometry StartPoint="0,10" EndPoint="100,10" /> 
     </Path.Data> 
    </Path> 
</Grid> 

或者在另一個控制把它包裝(CanvasPaths常用控件)與所需的高度:

<Grid Height="40" 
     VerticalAlignment="Center" 
     Background="LightCyan"> 
    <Canvas Height="20" VerticalAlignment="Center"> 
     <Path Stroke="Red" 
       StrokeThickness="20"> 
      <Path.Data> 
       <LineGeometry StartPoint="0,10" EndPoint="100,10" /> 
      </Path.Data> 
     </Path> 
    </Canvas> 
</Grid> 

,你是好去:

enter image description here

0

如果你的目標是你的期望,而不是你如何達到這個目標,我可能更喜歡你這個:

<Grid> 
    <Grid Height="40" Background="LightCyan" VerticalAlignment="Center"> 
     <Border BorderThickness="10" VerticalAlignment="Center" BorderBrush="Red" /> 
    </Grid> 
</Grid> 

enter image description here