StackPanel
control arranges child elements into a single line that can be oriented horizontally or vertically. When the Orientation
property is set to Vertical
(The default value is Vertical
), the VerticalAlignment
property of the button control will be invalid. Similarly, when the Orientation
property is set to Horizontal
, the HorizontalAlignment
property of the button control will be invalid.
If you add a button control into a StackPanel
, the HorizontalAlignment
property and VerticalAlignment
property of the button control will not work at the same time, that is, the button control can not be centered in a StackPanel
.
We suggest that you could add the button control to a Grid
panel, like this:
Grid gridPanel1 = new Grid();
Button TestButton = new Button();
TestButton.Content = "Test";
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
TestButton.VerticalAlignment = VerticalAlignment.Center;
gridPanel1.Children.Add(TestButton);
Window.Current.Content = gridPanel1;