WPF / Xaml,网格内的LineGeomtry垂直对齐不能正常工作

时间:2015-05-05 12:44:02

标签: wpf xaml

我尝试使用WPF创建自定义控件。我发现很多好的 网上的教程和建议,所以我开始宽度一个非常简单的例子来获得 我的手脏了,并得到一些练习。我发现问题偶然发生了 与自定义控件的主题无关。所以我将xaml代码解压缩为一个简单的wpf形式。

<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"

所以看起来我错过了关于线形或线条的细节。如何显示如下图所示的显示行?

"Expected result"

3 个答案:

答案 0 :(得分:0)

您需要将Width的{​​{1}}和HeightLineGeometry的{​​{1}}和Width相匹配,并设置{ {1}}属性Height

Path

enter image description here

答案 1 :(得分:0)

这里的问题是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

答案 2 :(得分:0)

如果你的目标是你的期望,而不是你达到这个目标的方式,我可能更喜欢你这个:

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

enter image description here