SharePoint Experts, Information Architects, Expert Witness

We provide consulting in a broad array of business and technology from architecture to design to deployment of global systems with a focus on surfacing data in the enterprise. Specialists in Microsoft, we are a premier provider of SharePoint Expertise (including 2016 and Office 365). We also provide Expert Witness/Legal Expert in eDiscovery, source discovery, patent infringement, piracy and more! We also have established SICG DLDS s.a. - our counterpart in Costa Rica that specializes in water systems (http://www.crwatersolutions.com) - Contact me direct: david_sterling@sterling-consulting.com or call 704-873-8846 x704.

Search This Blog

Thursday, November 18, 2010

Using Properties in Silverlight User Controls

When you are using Silverlight User Controls (or custom controls) you may have a need to pass properties between the main control and the user control (i.e. Main.xaml to MyCustom.xaml). If you are used to traditional SharePoint development, you are familiar with defining properties as so:
//// Resource Start Date:
private string _resrcStartDate = "";
public string ResourceStartDateIn
{
    get
    {
         return _resrcStartDate;
    }
    set    
    {
        _resrcStartDate = value;
    }
}

You will find that this works fine when you create a control via code or even if passing a 'hard coded' value to it - for example:
<local:MyCustomControl x:Name="CustControl" ResourceStartDateIn="01/01/2011" />

However, if you want to use this control for binding, for example using it in a DataGrid (or AgDataGrid), you'll find this does NOT work - in fact, in most cases, the project will simply crash without any indication of what is what. For example:

<local:MyCustomControl x:Name="CustControl" ResourceStartDateIn="{Binding Path=ResStartDate}" />

OR:

<local:MyCustomControl x:Name="CustControl" ResourceStartDateIn="{Binding Path=ResStartDate, Converter={StaticResource dateConverter}}" />

Note: the use of the dateConverter simply returns the date as a string - the first one assumes a true date.
The fix is really quite simple - Silverlight objects can pass values back and forth, but binding is another matter; in order to do this, Silverlight needs a "Dependency Property" it can use to maintain the information. To do this, simply change the way you define the property as so:

//
// Resource Start Date:
public static readonly DependencyProperty ResourceStartDateInProperty = DependencyProperty.Register("ResourceStartDateIn", typeof(string), typeof(MyCustomControl), null);
public string ResourceStartDateIn
{
    get { return (string)GetValue(ResourceStartDateInProperty); }
    set { SetValue(ResourceStartDateInProperty, value); }
}
//

NOTE: There is much more to the dependency property - this example is simply a quick and dirty for the SharePoint folks doing development.

1 comment:

Kurt said...

Thanks for this article!! Will help me a lot