Creating a Silverlight – WPF Button in code behind

In WPF or Silverlight, to add a Button from code behind insted of in XAML, first make sure the content control has a Children property. For example, I could not add to the SearchPanel Border control in the code below because it lacks such a property.

<Border Name="SearchPanel" CornerRadius="10" BorderBrush="Black" BorderThickness="1">
     <StackPanel Name="SearchStackPanel" />

Why’s that? Border inherits from System.Windows.FrameworkElement, which lacks, you guessed it, the Children property. However, StackPanel inherits from System.Windows.Controls.Panel, which does have it.

Now, to actually add the button:

Button RandomButton = new Button();
RandomButton.Name = "RandomButton";
RandomButton.Content = "Random Location";
RandomButton.Click += new RoutedEventHandler(RandomButton_Click);
RandomButton.Height = 25.0;
RandomButton.Width = 100.0;
private void Random_Click(object sender, RoutedEventArgs e)
     // Stuff
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: