Question

I want to create a kind of title by a TextBox and a Line (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>

The screen looks like this:

enter image description here

As you can see, the line is aligned to the middle row of the grid, but not to the middle of the text box.

I tried to put the text box VerticalAlignment="Center", and I tried to remove margin and padding, but nothing helped.

How can I center the line to middle of text box without defining it specifically by location?(Generically so that it will fit any size of line, and any size of text)

Was it helpful?

Solution

Try for Line set UseLayoutRounding="True":

Gets or sets a value that determines whether rendering for the object and its visual subtree should use rounding behavior that aligns rendering to whole pixels.

Example

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

Output

UseLayoutRounding="False"

enter image description here

UseLayoutRounding="True"

enter image description here

In this case, UseLayoutRounding makes one pixel line in the middle. If you want the Line to be crossed out text, then you need to swap the TextBox and Line, but also in this case you need to use UseLayoutRounding="True".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top