Brett
Brett

Reputation: 3316

Where to put WPF Dynamic Control Creation Code

I am just in the process of teaching myself WPF. I have reached the point of adding controls dynamically and have hit a brick wall on something really simple. I code that should create a button (shown below):

Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
parentControl.Add(button);

My question is what is parentControl actually called? I am using the standard Visual Studio 2012 WPF template and my main window is called MainWindow. I have no objects in the Window besides what comes in the template

So far I have looked at:

The closest I have found it: WPF runtime control creation.

All of these questions just assume you know such a basic thing but I don't. Please help.

Upvotes: 1

Views: 4592

Answers (1)

e_ne
e_ne

Reputation: 8459

I think I understand your question. If your XAML code looks like:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
</Window>

Then your codebehind should be something like:

public MainWindow()
{
    InitializeComponent();
    Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
    //In case you want to add other controls;
    //You should still really use XAML for this.
    var grid = new Grid();
    grid.Children.Add(button);
    Content = grid;
}

However, I warmly suggest you to use XAML as much as you can. Furthermore, I wouldn't add controls from the constructor but I'd use the Loaded event of the window. You can add a handler to the event in codebehind from the constructor, or directly in XAML. If you wanted to have the same result as above in XAML, your code would be:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Height="80" Width="180" Content="Test"/>
    </Grid>
</Window>

Upvotes: 4

Related Questions