如何根据TextBox的内容垂直对齐TextBox

时间:2017-03-31 06:16:30

标签: wpf

我有一个文本块我想垂直对齐,所以它出现在圆圈的中心。它是一个单个字符,例如'a','y','?','R'或任何其他有效字符。它可能有下降,上升,成为资本,非字母等。

使用以下代码,它似乎根据大写字母的高度对齐文本块。因此,小写字母显示得太低,带有下划线的字母更是如此。

enter image description here enter image description here

    <Grid Width="32" Background="Green"  Height="32">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Text="{Binding Character}" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
    </Grid>

有没有办法根据TextBlock的文本内容垂直对齐,而不是可能在其中的文本的保留区域?

如果不可能,WPF中有哪些其他控件/方法可用于实现此目的?

2 个答案:

答案 0 :(得分:0)

一个更适合我的样本 -

<ControlTemplate TargetType="{x:Type local:LevelControl}">
                <Viewbox x:Name="Frame">
                    <Grid Margin="2" Background="Transparent" VerticalAlignment="Center" HorizontalAlignment="Center" Width="26" Height="26">
                        <Ellipse x:Name="outerEllipse" Fill="{Binding Fill, ElementName=innerEllipse}" Stretch="UniformToFill" Grid.Row="0" Opacity="0.5" />
                        <Ellipse x:Name="innerEllipse" Fill="Gray" Stretch="UniformToFill" Margin="4" Grid.Row="0" />
                        <TextBlock x:Name="Label" FontWeight="Bold" FontSize="18" Foreground="White" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="7.948,0,7.698,2.125" />
                    </Grid>
                </Viewbox>

            </ControlTemplate>

或尝试使用标签<Label VerticalAlignment="Center" VerticalContentAlignment="Center" ></Label>

答案 1 :(得分:0)

只有当我为文本块设置magin时,你才能在代码中使用Landerah,而不是我可以在我想要的地方设置文本。你也可以动态设置边距,即如果字符是小写,则将magin位设置为像test.Margin = new Thickness(0,-2,0,0);

overflow: hidden