0

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

  • Although this question is probably easy to answer, it so hard to know where your understanding is at, that i am not sure any answer would help. Also there is a great need of more information on your part – TheGeneral Dec 27 '18 at 08:47
  • i will try to edit it – Patrick Jane Dec 27 '18 at 08:49
  • edited @TheGeneral – Patrick Jane Dec 27 '18 at 08:57
  • 1
    You have to add it to a container. How you do it depends on the container, eg. myWindow.AddChild(myButton) or myGrid.Children.Add(myButton). https://stackoverflow.com/questions/311131/add-wpf-control-at-runtime and https://www.wpf-tutorial.com/xaml/basic-xaml/ – Arie Dec 27 '18 at 08:59

1 Answers1

3

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);
Microgolf
  • 56
  • 2