1

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.

1
  • I don't know in what context you're using your code in (a longer example could help), but if you need to know the type of parentControl you can just use parentControl.GetType(). Commented Dec 30, 2012 at 22:10

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, thanks Eve :-) Can you explain why you warmly suggest using XAML as much as I can? Thanks again.
@Brett Use DataTemplates to generate controls on the fly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.