如何在C#中将文本框置于边框内

时间:2012-09-15 14:45:28

标签: c# windows-phone-7

在我的WP7应用中,我在Textbox内创建Border。如何将Textbox完全对齐Border的中心?

         Border rectangleborder = new Border();
         rectangleborder.Background = new SolidColorBrush(Colors.Transparent);
         rectangleborder.BorderBrush = new SolidColorBrush(Colors.Black);
         rectangleborder.BorderThickness = new Thickness(2);
         rectangleborder.Width = width;
         rectangleborder.Height = width;
         TextBox textbox = new TextBox();
         textbox.Text = "1";
         textbox.Background = new SolidColorBrush(Colors.Transparent);
         textbox.Foreground = new SolidColorBrush(Colors.Yellow);
         textbox.BorderBrush = new SolidColorBrush(Colors.Transparent);
         this.canvas1.Children.Add(rectangleborder);
         rectangleborder.SetValue(Canvas.LeftProperty, 30 + (j - 1) * width);
         rectangleborder.SetValue(Canvas.TopProperty, 30 + (i - 1) * width);
         rectangleborder.Child = textbox;

2 个答案:

答案 0 :(得分:2)

  TextBox textbox = new TextBox();
  textbox.HorizontalAlignment = HorizontalAlignment.Center;
  textbox.VerticalAlignment = VerticalAlignment.Center;

您还可以使用以下方式对齐文本: -

     textBox.TextAlign = HorizontalAlignment.Center;

答案 1 :(得分:1)

您需要将HorizontalAlignment设置为水平对齐,VerticalAlignment设置为垂直对齐:

TextBox textbox = new TextBox();
textbox.HorizontalAlignment = HorizontalAlignment.Center;
textbox.VerticalAlignment = VerticalAlignment.Center;

结果看起来应该是这样的:

enter image description here