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.

Community
  • 1
  • 1
Brett
  • 3,296
  • 5
  • 29
  • 45
  • 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()`. – e_ne Dec 30 '12 at 22:10

1 Answers1

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>
e_ne
  • 8,340
  • 32
  • 43
  • Awesome, thanks Eve :-) Can you explain why you warmly suggest using XAML as much as I can? Thanks again. – Brett Dec 30 '12 at 22:23
  • @Brett Refer to: http://stackoverflow.com/questions/6421372/why-to-avoid-the-codebehind-in-wpf-mvvm-pattern – e_ne Dec 30 '12 at 23:58
  • @Brett Use `DataTemplates` to generate controls on the fly. – ywm Jul 19 '13 at 17:13