中心元素位于另一个元素-WPF的中间

时间:2014-03-31 05:16:08

标签: wpf mvvm binding element

我想通过TextBoxLine WPF )创建一种标题。

<Grid>
    <Grid.Resources>
        <Style x:Key="labelTextbox" TargetType="{x:Type TextBox}" >
            <Setter Property="IsReadOnly" Value="True"/>
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Margin" Value="10,0,0,0"/>
            <Setter Property="Padding" Value="4,1,5,1"/>
        </Style>
    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Line  X1="5" X2="5000" VerticalAlignment="Center" StrokeThickness="1" Stroke="Gray"/>
    <TextBox Text="Buttons" Style="{StaticResource labelTextbox}"/>
    <Grid Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Margin="10" Content="Button A"/>
        <Button Margin="10" Content="Button B" Grid.Row="1"/>
        <Button Margin="10" Content="Button C" Grid.Row="2"/>
        <Button Margin="10" Content="Button D" Grid.Row="3"/>
    </Grid>
</Grid>

屏幕看起来像这样:

enter image description here

如您所见,该行与网格的中间行对齐,但不与文本框的中间对齐。

我尝试放置文本框VerticalAlignment="Center",我尝试删除边距和填充,但没有任何帮助。

如何将行居中放置在文本框的中间而不是按位置专门定义?(一般来说它适合任何大小的行,以及任何大小的文本)

1 个答案:

答案 0 :(得分:2)

尝试Line设置UseLayoutRounding="True"

  

获取或设置一个值,该值确定对象及其可视子树的渲染是否应使用将渲染与整个像素对齐的舍入行为。

<强> Example

<Line UseLayoutRounding="True"
      X1="5" X2="5000" ... />

<强> Output

UseLayoutRounding="False"

enter image description here

UseLayoutRounding="True"

enter image description here

在这种情况下,UseLayoutRounding在中间生成一条像素线。如果您希望将Line划掉文本,则需要交换TextBox和Line,但在这种情况下,您还需要使用UseLayoutRounding="True"