Adding text to WPF Line

北战南征 提交于 2019-12-12 01:54:17

问题


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?


回答1:


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../>




回答2:


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


来源:https://stackoverflow.com/questions/27251787/adding-text-to-wpf-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!