Get binding expressions of DependencyObject instances in Silverlight

by Geert 22. December 2011 19:11

Recently, I needed to retrieve binding information on a dependency property in a behavior. In WPF, this is all possible (of course) via the BindingOperations.GetBindingExpression method. However, the developers of Silverlight must have thought that developers are only interested in binding expressions starting from a FrameworkElement. So, this means you cannot get binding expressions from the following types while they can have bindings:

  • DependencyObject
  • UIElement
  • Behavior
  • TriggerAction
  • TriggerBase

And much more. For a complete list, see this list.

Anyway, I was pretty sad that the Silverlight team decided for me that I would never need to check the binding expression inside a behavior (which I needed in this case). Anyway, below is an extension method that allows you to get the binding expression of any dependency property:

   1: /// <summary>
   2: /// Gets the binding expression for the specified dependency property.
   3: /// </summary>
   4: /// <param name="dependencyObject">The dependency object.</param>
   5: /// <param name="dependencyProperty">The dependency property.</param>
   6: /// <returns>
   7: /// The <see cref="BindingExpression"/> or <c>null</c> if the property is not bound.
   8: // </returns>
   9: /// <exception cref="ArgumentNullException">The <paramref name="dependencyObject"/> is <c>null</c>.</exception>
  10: /// <exception cref="ArgumentNullException">The <paramref name="dependencyProperty"/> is <c>null</c>.</exception>
  11: public static BindingExpression GetBindingExpression(this DependencyObject dependencyObject, DependencyProperty dependencyProperty)
  12: {
  13:     Argument.IsNotNull("dependencyObject", dependencyObject);
  14:     Argument.IsNotNull("dependencyProperty", dependencyProperty);
  15:  
  16:     return (dependencyObject.ReadLocalValue(dependencyProperty) as BindingExpression);
  17: }

Of course, this extension method is included in Catel.

Tags:

C# | Silverlight

Pingbacks and trackbacks (2)+

Comments are closed

About the Author

Geert van Horrik is an independent freelance software developer since January 1st, 2007. Since then he was been working on several projects from C++ to C# (WPF, Silverlight, ASP.NET, etc). Currently he loves to write his software using WPF (or Silverlight if WPF isn't an option).

Lately, Geert is spending a lot of time on Catel, a free open-source MVVM Framework for WPF and Silverlight. Actually, it's more than "just" an MVVM Framework, it's a complete application library!