c# - 如何将 TextBlock 居中到给定位置

标签 c# wpf silverlight

TextBlock 应该以 x 位置为中心(或者当 Orientation 为垂直时为 y)。 我实现了:

TextBlock text = new TextBlock();
// Some code to define text, font, etc. here

// Turn if Orientation is vertical
if (Orientation == Orientation.Vertical) 
{
  text.RenderTransform = new RotateTransform() { Angle = 270 };
}

// Update, then ActualWidth is set correctly
text.UpdateLayout();

// Position of label centered to given position
double halfWidth = text.ActualWidth / 2;
double x1 = (Orientation == Orientation.Horizontal) ? x - halfWidth : x;
double y1 = (Orientation == Orientation.Horizontal) ? y : y + halfWidth;

Canvas.SetLeft(text, x1);
Canvas.SetTop(text, y1);

Children.Add(text); // Add to Canvas

这实际上工作正常,但是否可以在没有 UpdateLayout 的情况下执行此操作。如果我删除 UpdateLayout,那么我就得不到我正在寻找的位置,因为 ActualWidth(当然)为零。

最佳答案

您可以通过将 Canvas.Top/Canvas.Left 值绑定(bind)到 TextBlock 的 ActualWidth/ 来做到这一点ActualHeight 并使用 Converter

这是一个例子。我正在使用我通常用于数学公式的自定义 MathConverter(代码可以在 here 中找到),但您也可以使用普通转换器,它返回传递的任何值的一半。

<Style TargetType="{x:Type TextBlock}">
    <Style.Triggers>
        <Trigger Property="Orientation" Value="Horizontal">
            <Setter Property="Canvas.Left" 
                    Value="{Binding RelativeSource={RelativeSource Self}, 
                    Path=ActualWidth,
                    Converter={StaticResource MathConverter}, 
                    ConverterParameter=@VALUE/2}" />
        </Trigger>
        <Trigger Property="Orientation" Value="Vertical">
            <Setter Property="Canvas.Top" 
                    Value="{Binding RelativeSource={RelativeSource Self}, 
                    Path=ActualHeight,
                    Converter={StaticResource MathConverter}, 
                    ConverterParameter=@VALUE/2}" />
        </Trigger>
    </Style.Triggers>
</Style>

编辑

只需重新阅读问题并意识到您正试图将 TextBlock 置于 Canvas 上特定 x,y 坐标的中心。在这种情况下,您需要实现一个 MultiConverter 而不是常规的 Converter,这样您就可以向它传递两个参数:X/Y 值和 ActualHeight/实际宽度值

关于c# - 如何将 TextBlock 居中到给定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390542/

相关文章:

c# - Android 上类似的 EventToCommand(行为)

C# 下载器 : should I use Threads, BackgroundWorker 还是 ThreadPool?

c# - 初始化 List<Child Class> 到 List<Parent Class>

c# - .Net Core MVC反序列化

c# - LINQ to SQL 类,如何更改列格式? (数据网格)

c# - tabcontroller 中的两个选定选项卡

wpf - 组合框,连续多个项目

c# - 在 Windows Phone 应用程序中编写 Xml

silverlight - 为什么使用 "RIA Services Link"而不仅仅是 OData 端点?

silverlight - "Inheritor of the ResourceDictionary is expected"- 这个错误是什么意思