Reputation:
I created a UWP solution and created a button. There are no problems with the buttons.
I do not know how to center the button in the window.
Code
StackPanel stackPanel1 = new StackPanel();
Button TestButton = new Button();
TestButton.Content = "Test";
stackPanel1.Children.Add(subscribeButton);
Window.Current.Content = stackPanel1;
Upvotes: 2
Views: 666
Reputation: 3032
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;
Upvotes: 0
Reputation: 76
This line is all you need.
TestButton.HorizontalAlignment = HorizontalAlignment.Center;
Upvotes: 1
Reputation: 9077
You can set HorizontalAlignment
something like these inside the stackpanel...
<StackPanel Margin="10,0,0,0" Orientation="Horizontal" Grid.Column="0">
<TextBlock Grid.Column="1" Grid.Row="0" FontSize="16" HorizontalAlignment="Center">2. Draw a pattern</TextBlock>
<Button x:Name="DeleteSiteButton" Content="Delete Site"
HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Top" Click="DeleteSiteButton_Click"/>
<Button x:Name="AddSiteButton" Content="Add Site" HorizontalAlignment="Right"
Margin="10,0,0,0" VerticalAlignment="Top" Click="AddSiteButton_Click"/>
</StackPanel>
Upvotes: 0
Reputation: 76
Changing the position of the button to half of the form's width and height will work.
Point point = new Point(this.Width / 2 - (button1.Width/2), this.Height / 2 - (button1.Height/ 2));
button1.Location = point;
The added - (button1.Width/2)
is because the button's position is based on the upper right hand corner of the button, and not actually the center.
Upvotes: 0