Did You Know That… you can create Silverlight objects programmatically?

In both Silverlight 1.0 and Silverlight 2.0 it is possible to create Silverlight objects programmatically, in the former using JavaScript and in the latter using, for example, C#.

Creating objects programmatically in Silverlight 1.0 is non-trivial, as demonstrated in this  How Do I video.

Creating objects programmatically in Silverlight 2.0 is far easier, because each XAML object is represented by a CLR object which you can instantiate in whatever language you are using, for example C#.

Ellipse myEllipse = new Ellipse();
parentCanvas.Children.Add(myEllipse);
myEllipse.Width = 120;
myEllipse.Height = 50;
myEllipse.SetValue(LeftProperty, 150);
myEllipse.SetValue(TopProperty, 10);
myEllipse.StrokeThickness = 2;
myEllipse.Stroke = new SolidColorBrush(Colors.Blue);

An early demonstration of dynamic instantiation of Silverlight objects is shown in this How Do I video.

I recently received an inquiry from a developer asking about the relative merits of declaring Silverlight objects in XAML versus doing so programmatically.  Some of the developers in his organization were arguing that it was better to declare all of the objects programmatically "so that they can have more control."

I responded that the point of instantiating Silverlight objects in code-behind is that you can create these objects in response to events that occur while your program is running. The disadvantage is that it is much more difficult to create or manipulate your objects with tools such as Expression Designer, and I'm not convinced that you give up any level of control by creating theobjects at design time.

Fortunately, you are not forced into an either/or choice; you can create your objects using a design tool and then, at runtime,  either manipulate those objects or create new objects in response to events.

Personally, I would resist the idea of creating every object programmatically, as I suspect that the medium to long-term maintenance costs would be very high, as you would be unnecessarily surrendering the advantages of utilizing powerful design tools; but of course this is a generalization  that would have to be evaluated for each particular project.

kick it on DotNetKicks.com

Share

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.