Creating XAML Objects in Code

One of the advantages that Silverlight 1.1 does bring to the party is the the isomorphism between XAML and CLR object that is found in Windows Presentation Framework (WPF). Thus, you can create a rectangle declaratively,

<Rectangle x:Name="myRect" Width="120" Height="50" Canvas.Left="10"
              Canvas.Top="10" StrokeThickness="2" Stroke="Black"  >
        <GradientStop Color="Red" Offset="0.0"/>
        <GradientStop Color="Orange" Offset="0.2"/>
        <GradientStop Color="Yellow" Offset="0.4"/>
        <GradientStop Color="Green" Offset="0.6"/>
        <GradientStop Color="Blue" Offset="0.8"/>
        <GradientStop Color="Purple" Offset="1.0"/>

or you can create the same object programatically,

// declare the rectangle
Rectangle myRectangle = new Rectangle();

 // add it to the canvas  

// set properties
myRectangle.Width = 120;  
myRectangle.Height = 50;

// set dependency properties
myRectangle.SetValue(LeftProperty, 150);  
myRectangle.SetValue(TopProperty, 10);

// create a Linear Gradient Brush
LinearGradientBrush lgb = new LinearGradientBrush();

// Create a series of GraidentStop objects
GradientStop gs1 = new GradientStop();  
GradientStop gs2 = new GradientStop();
// ...

// Set the color for each stop object
gs1.Color = Colors.Red;
gs2.Color = Colors.Orange;
// Set the offset for each stop object
gs1.Offset = 0.0;
gs2.Offset = 0.2;
// ....

// Add the Gradient stops to the Linear Gradient Brush

// Set the Fill property of MyRectangle to the LinearGradientBrush object
myRectangle.Fill = lgb;

The advantage of being able to create the object programmatically of course is that it makes it much easier to create objects dynamically, in response to events that arise while your program is running.  In  my latest video I explore this aspect of the relationship between XAML and managed code and more.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was 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 and a Microsoft MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.