Patrick Jane
Patrick Jane

Reputation: 61

Creating button and placing it on certain xaml window without using xaml code

I made a button, set up his margins, height, width in my Window.xaml.cs file:

Button b = new Button();
b.Margin = new Thickness(10, 10, 10, 10);
b.Content= "Button";
b.Height = 50;
b.Width = 50;

I want it to show up on my Window.xaml window when i start the program. Using only these few properties is not showing it.

I could go in Window.xaml file and type in grid or wherever:

<Button Margin="10,10,10,10" Content="Button" Height="50" Width="50"></Button>

And it would show this button in the widnow, but using only these properites (in .cs code), is not enough

Upvotes: 0

Views: 141

Answers (1)

Microgolf
Microgolf

Reputation: 56

I assume you only instantiated the button. The button doesn't know where it should be on the screen. It must be assigned to a named parent control like a grid or stackpanel.

XAML:

<Window>
<Grid x:Name="RootGrid">
</Grid>
</Window>

Code behind:

RootGrid.Children.Add(b);

Upvotes: 3

Related Questions