wpf 如何在 Grid 中居中 TextBox 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18856543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:40:04  来源:igfitidea点击:

How to center TextBox element inside Grid

c#wpfwindows-phone-8

提问by user2756598

I'm developing WP8 app for my own needs and want it to have small live tile with text. Since small tile cannot display text, I'm generating appropriate image with needed text. Here is the code:

我正在根据自己的需要开发 WP8 应用程序,并希望它具有带有文本的小型动态磁贴。由于小磁贴无法显示文本,我正在生成带有所需文本的适当图像。这是代码:

WriteableBitmap bmpSmall = new WriteableBitmap(159, 159);
var grid = new Grid();
grid.Width = bmpSmall.PixelWidth;
grid.Height = bmpSmall.PixelHeight;

var background = new Canvas();
background.Width = bmpSmall.PixelWidth;
background.Height = bmpSmall.PixelHeight;

SolidColorBrush backColor = new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"]);
background.Background = backColor;

var textBlock = new TextBlock();
textBlock.Text = "qwerty";
textBlock.FontWeight = FontWeights.Bold;
textBlock.HorizontalAlignment = HorizontalAlignment.Center;
textBlock.VerticalAlignment = VerticalAlignment.Center;
textBlock.FontSize = 28;
textBlock.Foreground = new SolidColorBrush(Colors.White);

grid.Children.Add(textBlock);
bmpSmall.Render(background, null);
bmpSmall.Render(grid, null);
bmpSmall.Invalidate();

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/smallTile.jpg", System.IO.FileMode.Create, isf))
    {
        bmpSmall.SaveJpeg(imageStream, 159, 159, 0, 100);
    }
}

ShellTile tile = ShellTile.ActiveTiles.First();
FlipTileData tileData = new FlipTileData();
tileData.SmallBackgroundImage = new Uri(@"isostore:/Shared/ShellContent/smallTile.jpg", UriKind.Absolute);
tile.Update(tileData);

And result looks like:

结果如下:

enter image description here

在此处输入图片说明

As you see, text is aligned to top left corner. The question is "Why"? Since I'd set textBlock.HorizontalAlignmentand textBlock.VerticalAlignment- I expect it in the center of the image. For example the following XAML looks like you can expect and like I need:

如您所见,文本与左上角对齐。问题是“为什么”?因为我设置了textBlock.HorizontalAlignment并且textBlock.VerticalAlignment- 我希望它位于图像的中心。例如,下面的 XAML 看起来像你可以期待的,就像我需要的一样:

<Grid Width="159" Height="159">
    <Grid.Background>
        <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
    </Grid.Background>
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" FontSize="28" Foreground="White">qwerty</TextBlock>
</Grid>

What did I miss? How can I center text?

我错过了什么?如何使文本居中?

采纳答案by codechinchilla

Give the following code a try:

试试下面的代码:

       WriteableBitmap bmpSmall = new WriteableBitmap(159, 159);
        var grid = new Grid();
        grid.Width = bmpSmall.PixelWidth;
        grid.Height = bmpSmall.PixelHeight;

        var background = new Canvas();
        background.Width = bmpSmall.PixelWidth;
        background.Height = bmpSmall.PixelHeight;

        SolidColorBrush backColor = new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"]);
        background.Background = backColor;

        var textBlock = new TextBlock();
        textBlock.Width = bmpSmall.PixelWidth;

        textBlock.Text = "qwerty";
        textBlock.FontWeight = FontWeights.Bold;
        textBlock.HorizontalAlignment = HorizontalAlignment.Stretch;
        textBlock.VerticalAlignment = VerticalAlignment.Center;
        textBlock.FontSize = 28;
        textBlock.Foreground = new SolidColorBrush(Colors.White);
        textBlock.TextAlignment = TextAlignment.Center;
        grid.Children.Add(background);
        grid.Children.Add(textBlock);
        grid.Measure(new Size(bmpSmall.PixelWidth, bmpSmall.PixelHeight));
        grid.Arrange(new Rect(0,0,bmpSmall.PixelWidth, bmpSmall.PixelHeight));
        grid.UpdateLayout();
        bmpSmall.Render(grid, null);
        bmpSmall.Invalidate();

I set the TextBlockwidth to the same as the rest of the tile, and set HorizontalAlignmentto stretch, so that control would take up the whole width of the tile. Then I set the TextAlignmentproperty to TextAlignment.Center, in order to center the text. Hope that helps!

我将TextBlock宽度设置为与磁贴的其余部分相同,并设置HorizontalAlignment为拉伸,以便控件占据磁贴的整个宽度。然后我将该TextAlignment属性设置为TextAlignment.Center,以使文本居中。希望有帮助!

Edit: Apparently for writable bitmaps, you must do the measure/arrange/layout steps yourself in order to render controls as you would think they should be rendered. Give this updated code a try, it should work this time!

编辑:显然对于可写位图,您必须自己执行测量/排列/布局步骤,以便按照您认为应该呈现的方式呈现控件。试试这个更新的代码,这次应该可以了!

回答by Nitin

You will have to set the HorizontalAlignment="Stretch" VerticalAlignment="Stretch"for grid also. Currently grid is only of size of its content i.e textblock.

您还必须设置HorizontalAlignment="Stretch" VerticalAlignment="Stretch"for 网格。目前网格只有其内容的大小,即textblock.

回答by Sheridan

After copying your code into an empty WPF application, I'm afraid to tell you that your code works just fine:

将您的代码复制到一个空的 WPF 应用程序后,我不敢告诉您您的代码运行良好:

enter image description here

在此处输入图片说明

All I did was to set the Grid.Backgroundto red and the TextBlock.Backgroundto black to clarify the situation:

我所做的只是将 设置Grid.Background为红色和TextBlock.Background黑色以澄清情况:

<Grid Width="159" Height="159">
    <Grid.Background>
        <SolidColorBrush Color="Red"/>
    </Grid.Background>
    <TextBlock Background="Black" HorizontalAlignment="Center" 
        VerticalAlignment="Center" FontWeight="Bold" FontSize="28" 
        Foreground="White">qwerty</TextBlock>

Therefore, I can only assume that you have a problem elsewhere in your code.

因此,我只能假设您的代码中的其他地方有问题。

UPDATE >>>

更新 >>>

Sorry, you're right, I didmisunderstand you. However, after testing your C#code, the story is just the same:

对不起,你说得对,我确实误会了你。然而,在测试你的C#代码之后,故事是一样的:

enter image description here

在此处输入图片说明

This mightlook like the same image, but it actuallycomes from yourC#code... I made a couple of little changes, but nothing that affected the position of the TextBlock:

可能看起来像相同的图像,但它实际上来自您的C#代码......我做了一些小改动,但没有影响 的位置TextBlock

Grid grid = new Grid();
grid.Background = Brushes.Red;
grid.Width = grid.Height = 159.0;
TextBlock textBlock = new TextBlock();
textBlock.Text = "qwerty";
textBlock.Background = Brushes.Black;
textBlock.FontWeight = FontWeights.Bold;
textBlock.HorizontalAlignment = HorizontalAlignment.Center;
textBlock.VerticalAlignment = VerticalAlignment.Center;
textBlock.FontSize = 28;
textBlock.Foreground = Brushes.White;
grid.Children.Add(textBlock);
this.Content = grid;

If you put this code into a new WPF project, you'll see that it works just fine, so that only leaves your WriteableBitmapobject as the culprit of this problem... what are you using that for? If you're just adding it to your UI, then you can simply add the controls to the Windowdirectly.

如果您将此代码放入一个新的 WPF 项目中,您会发现它工作得很好,因此只会让您的WriteableBitmap对象成为这个问题的罪魁祸首……您使用它做什么?如果您只是将它添加到您的 UI,那么您可以直接将控件添加到Window