WPF C#TextBlock对齐不起作用?

时间:2014-08-16 19:07:45

标签: c# wpf textblock

我正在研究WPF中的一个小项目,我只能在C#中工作,但很少有令人困惑的事情。对齐似乎对某些元素根本不起作用,尤其是TextBlock。有时TextAlignment有效,但就是这样。我不确定是什么问题。我使用的部分代码:

public static Canvas buttonRightPanelTile(this Canvas tile)
    {
        tile.Background = new SolidColorBrush(Color.FromArgb(255,50,50,50));
        tile.Height = 100;
        tile.Width = 100;

        TextBlock title = new TextBlock();
        title.Text = "Další\nfunkce";
        title.FontSize = Window.Current.Bounds.Height / 36;
        title.Foreground = new SolidColorBrush(Colors.White);

        title.HorizontalAlignment = HorizontalAlignment.Center;
        title.VerticalAlignment = VerticalAlignment.Center;
        title.TextAlignment = TextAlignment.Center;

        tile.Children.Add(title);


        return tile;
    }

有三个对齐,其中没有对齐会影响切片中的文本位置。瓷砖本身位于网格单元中并且正确对齐。

提前感谢您的建议。

1 个答案:

答案 0 :(得分:1)

Canvas不适合动态尺寸布局 。它不会坚持对齐。

它应该仅用于固定大小的布局。对于 动态布局,您应该使用网格

要在Canvas上对齐控件,您必须将控件的Top和Left设置为某些绝对位置,如:

Canvas.SetLeft(title, tile.ActualWidth / 2);
Canvas.SetTop(title, tile.ActualHeight / 2);

根据您的方便需要在画布中心对齐控件时,为计算添加一些偏移量。

相关问题