Creating Controls Dynamically
In Silverlight 2, anything you can create in XAML you can create in code.
Thus, where you might write this in XAML:
<Button x:Name="myButton" Content="Hello" />
You can also write this in code:
Button myButton = new Button(); myButton.Content = "Hello";
You could create all of your objects in code, but even though it takes some getting used to, writing them in XAML has tremendous advantages. The most significant is that XAML is highly toolable. A toolable language lends itself to being manipulated and maintained by tools such as Expression Blend and Visual Studio 2008, and that makes for programs that are much easier to maintain.
That said, you will still need to create objects dynamically when you can't know at design time which objects, or how many, are required. This is especially true with data-driven applications, where the design of the form or the user interface will be dictated by user interactions and lookups in a database.
In the next example, you'll ask the user which platform he is building for ("Web" or "Desktop") and then dynamically create checkboxes based on the user's choice, as shown in Figure 7-16.
Figure 7-16. Dynamic creation of controls
If the user clicks on "Web," you dynamically create two checkboxes in a StackPanel
and add them to the righthand column of the Grid
. If the user clicks on "Desktop," you clear that column and fill the StackPanel ...
Get Programming .NET 3.5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.