Adding text to WPF Line

2019-09-18 08:48发布

How do I add text to a Line UIElement? I would like to have the text placed in the middle of the line.

<Line Stroke="Black" X1="{Binding From.CanvasCenterX}" Y1="{Binding From.CanvasCenterY}" X2="{Binding To.CanvasCenterX}" Y2="{Binding To.CanvasCenterY}" StrokeThickness="2" />

Is this possible?

2条回答
我想做一个坏孩纸
2楼-- · 2019-09-18 09:23

You need to set X2 coordinate value based on length of Text for alignment.

<Line Stroke="Black" 
    X1="{Binding From.CanvasCenterX}" Y1="{Binding From.CanvasCenterY}"
    X2="{Binding To.CanvasCenterX}" Y2="{Binding To.CanvasCenterY}" StrokeThickness="2" />

<TextBlock Text="Line Between the Text!" 
     VerticalAlignment="Center" HorizontalAlignment="Center"/>

<Line Stroke="Black" 
    X1="{Binding From.CanvasCenterX}" Y1="{Binding From.CanvasCenterY}" 
    X2="{Binding To.CanvasCenterX}" Y2="{Binding To.CanvasCenterY}" StrokeThickness="2" />
查看更多
做自己的国王
3楼-- · 2019-09-18 09:32

The following XAML code adds text to a Line UIElement. In this example the text is presented by a <TextBlock... />. The text is centered at the Line, but this can easily be changed by the TextAlignment property.

<Grid>
    <TextBlock Text="{Binding RelationName}" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    <Line Stroke="Black" X1="{Binding From.CanvasCenterX}" Y1="{Binding From.CanvasCenterY}" X2="{Binding To.CanvasCenterX}" Y2="{Binding To.CanvasCenterY}" StrokeThickness="2" />
</Grid>

VerticalAlignment and HorizontalAlignment places the <TextBlock../> in the <Grid../>

查看更多
登录 后发表回答