Creating Controls in Code

In my new video I demonstrate how you can create controls dynamically at run time. The technique is very straight forward, everything you can create declaratively in XAML you can also create dynamically in C#.

xaml

<Button x:Name="Button1" Width="50" Height="30" Content="Click Me" Grid.Row="3" Grid.Column="0" />

C#

Button button2 = new Button();
button2.Width = 75;
button2.Height = 30;
button2.Content = "No, click me!";
button2.SetValue(Grid.RowProperty, 0);
button2.SetValue(Grid.ColumnProperty, 1);
LayoutRoot.Children.Add(button2);

TwoButtons

 

Why Not Dynamically Instantiate All of 'Em?

The case for why you must dynamically instantiate some objects is clear: there are times you just can't know at design time what kind of object you'll need: you must respond to the user's choices and actions. That of course raises the question of why not eschew the XAML altogether and dynamically instantiate all your objects.

There are two answers to this. The first is that it is faster and easier to declare the button in XAML. The second, more important answer is that the XAML is "toolable" — that is, the XAML can be read and understood by, for example, Expression Blend, while the C# cannot; which makes developing large applications far easier and far more scalable.

If I open the project that created these two buttons in Blend, this is what I see:

DynamicInBlend

 

Blend can read the grid, and the button declared in XAML but is totally unaware of the button created in code.

Conclusion?

The short conclusion is to create objects declaratively at design time when possible, and dynamically at runtime when necessary.  In the abstract this can seem confusing, but when writing code, it is never ambiguous.

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *