Silverlight: Databinding in C#

Recently I had to bind properties from a Dependency Object to a Silverlight Control from code. Although it is relatively easy, I had to search for the syntax.

To make data binding work in Silverlight you need dependency properties and for dependency properties to work you need to inherit at least from DependencyObject.

My source class was a regular POCO (Plain-old-CLR-object) that had to be changed to inherit from DependencyObject. The target was a custom SL Control which implicitly inherits from DependencyObject.

The next step was to replace my standard properties into Dependency Properties. There is a code snippet in VS to generate this. Type the following in your VS Code editor and a dependency object template will expand.


public int Example
    get { return (int)GetValue(ExampleProperty); }
    set { SetValue(ExampleProperty, value); }

// Using a DependencyProperty as the backing store for Example.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty ExampleProperty =
    DependencyProperty.Register("Example", typeof(int), 
    typeof(ExampleClass), new PropertyMetadata(0));

Now that we have a source class inheriting from DependencyObject and having a Dependency Property we can hook this up to a control. I will show you the code…

// Create a binding for SOURCE property
var exampleBinding = new Binding("Example")
    Source = ExampleObject,   // SOURCE OBJECT
    Mode = BindingMode.TwoWay // Direction
// Assign the binding to Target Control ExampleControl.SetBinding( ExampleControl.ExampleProperty, // Target dependency prop exampleBinding); // Source Binding

So in this code above two things are happening. First a new Binding object is created with the name of the property from the source, the instance of the source itself and optionally the binding mode (I want to be explicit).

The second step is to assign the Binding to another DependencyObject’s property, where the ExampleControl.ExampleProperty is pointing to the static part of the dependency property. If you look at the first code snippet with the expanded DP, you see the ‘static read-only DependencyProperty’ field. This is where you bind with.

Maybe in a future article I can go into the way data binding and all that dependency stuff is working internally, which is not that complicated, but a lot of implications.

Hope this will help you get started with data binding from C#. If you miss something let me know!


About this entry