A way to specify UI elements as properties declaratively in XAML

Here is an screenshot of an icon button type UserControl I developed in Silverlight:

This shows nine instances of the same UserControl, which is composed of a TextBlock and a panel containing an icon. The content of both of these are specified via properties. The challenge was to enable the panel to be specified declaratively in XAML. The problem was that you can’t use UI elements as static resources in Silverlight. For example, the following approach results in a runtime error:

<local:IconButton IconPanel="{StaticReource RectangleIcon}" Command="AddRectangle" Caption="Rectangle"/>

However, using a TypeConverter, I devised a way to allow the control to be specified like this:

<local:IconButton IconPanel="RectangleIcon" Command="AddRectangle" Caption="Rectangle"/>

A good general introduction to using Typeconverters with XAML is in Umair Saeed’s blog. The implementation of the TypeConverter class here is adapted from the generic example on that page.

//The TypeConverter class is in the System.ComponentModel namespace. The CultureInfo class is in System.Globalization.

public class IconConverter : TypeConverter
{
   public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   {
      if (sourceType == typeof(string))
      {
         return true;
      }
      return base.CanConvertFrom(context, sourceType);
   }

   public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   {
      string strValue;
      if (value is string)
      {
         strValue = (string)value;
         if (strValue == "RectangleIcon")
            return Icons.Rectangle; 
         else
            return new Grid();
      }
      return base.ConvertFrom(context, culture, value);
   }

The Icons class just gives a convenient way of referring to the Icons. The code below can return a UserControl, or the root element from it. Note that in the latter case that you need to remove the root element from the created UserControl Instance, or an error will be generated: A UI element cannot be contained in multiple UI elements.

The RectangleIcon class it refers to is a UserControl just containing the Grid with the rectangle.

Lastly, here is how the implementation of the IconPanel property in the IconButton class:

private Panel _iconPanel;

[TypeConverter(typeof(IconConverter))]
public Panel IconPanel
{
   get
   {
      return _iconPanel;
   }
   set
   {
       _iconPanel = value;
       IconHolder.Content = _iconPanel;
    }
}

IconHolder is an empty UserControl which will hold the icon. Adding it directly as a child to the root element is also possible – however you need to make sure the names of the panels are different. Otherwise you may try to add a grid named LayoutRoot to another grid named LayoutRoot – which results in the error “Value does not fall within expected range” being thrown at runtime.

 

[Edited 21 July 2019 – restored image and code excerpts]

15 Replies to “A way to specify UI elements as properties declaratively in XAML”

  1. I have read all the 4 Chapters and it was exeellcnt, awaiting for your next Article, will be happy if i get to know more about styling the controls and basic layout designing

      1. Agreed, I first saw this and thought oooh a pldeeover reference for Silverlight, I’ll print that and put it on my wall I then scanned over the PNG and saved the ink.I think a poster identifying the object and event models and maybe the boundaries between Silverlight and WPF would be useful, not some marketing hype.

    1. Hi Adam,I just came a across your blog htuorgh a google search. Thank you so much, it is a great resouce. I’m thinking of designing a silverlight mobile application using expression blend, which will help foreigners get from city centre to our business. Are there any tutorials or examples that may help me?

      1. You might look at integration with Bing Maps. There are a couple of articles on MSDN on that topic. You might find useful code on codeplex.com or in the samples on the silverlight.net. There are also forums on silverlight.net that might be useful. Other resources include silverlightshow.net and silverlightCream.com which are aggregators of silverlight-related content on the Web.
        [My name is Peter btw]

      2. To piggyback on Michael’s comenmt. We’re also working with Kurt Shifflett and John Papa on about 2.5 hours of some killer MVVM sessions. And David Platt along with some members of the Prism team will be delivering a half-day hands-on workshop on Prism. And all this for only $699 if you register before the end of August. Let me know if you have any questions.

    1. Howdy Darryl,For silverlight 2, have they added WPF dagdtrias out-of-box. I was shocked to find that xceed dagdtrias were needed to use the datagrid WPF control and there is no longer a free version for use. IMO, this is a huge setback for WPF adoption and a possible adoption killer for small shops. If I missed something with this stance, please enlighten.- Johnathan

  2. Hi there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any methods to protect against hackers?

  3. Pingback: URL

Leave a Reply

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