How to get a list of Bindings in WPF?

Tonight I was struggling with how to get a list of Bindings defined within a WPF form. Why do I want to do this? Well there are two reasons.

  1. I want to be able to evaluate each binding and use the meta-data defined on the business entity to “decorate” the bound control. For example, a description of the business entity property (defined using an attribute) could be applied as the default tooltip on the control to which it is bound. This can (and in the WinForms world I have) be taken much further to determine the data source for lookup fields, label text, maximum input lengths or masks etc.
  2. If I validate a business entity and it returns a list of validation errors I want to be able to use the validation “context” (the instance type and property name) to be able to highlight the relevant bound control (if any) as being in error.

In WinForms determining all Bindings for a given top level control is reasonably straight forward by iterating through the controls and examining the BindingContext’s CurrencyManager’s Bindings collection. Normally a WinForm will only have a small number (e.g. 1) BindingContext that is inherited by child container controls.

In WPF I couldn’t find anything obvious. There is a likely sounding BindingOperations static class which provides several helper methods but none seem to do the trick.

The solution I ended up with before resorting to Google was to use reflection as follows…

private static ValidationBindingContext GetBindingForProperty(Type boundType, string boundPropertyName, 
FrameworkElement root) { foreach (FrameworkElement element in LogicalTreeHelper.GetChildren(root).OfType<FrameworkElement>()) { FieldInfo[] properties = element.GetType().GetFields(BindingFlags.Public | BindingFlags.GetProperty |
BindingFlags.Static | BindingFlags.FlattenHierarchy); foreach (FieldInfo field in properties) { if (field.FieldType == typeof(DependencyProperty)) { DependencyProperty dp = (DependencyProperty)field.GetValue(null); if (BindingOperations.IsDataBound(element, dp)) { BindingExpression bindingExpression = BindingOperations.GetBindingExpression(element, dp); if (boundType == bindingExpression.DataItem.GetType()) { if (boundPropertyName == bindingExpression.ParentBinding.Path.Path) { return new ValidationBindingContext(bindingExpression, element as UIElement); } } } } } // Not found so check all child elements ValidationBindingContext bindingContext = GetBindingForProperty(boundType, boundPropertyName, element); if (bindingContext != null) return bindingContext; } return null; }

I thought maybe it would look less horrendous if I used LINQ…

private static ValidationBindingContext GetBindingForPropertyLINQ(Type boundType, string boundPropertyName, 
FrameworkElement root) { foreach (FrameworkElement element in LogicalTreeHelper.GetChildren(root).OfType<FrameworkElement>()) { var result = from FieldInfo field in element.GetType().GetFields(BindingFlags.Public | BindingFlags.GetProperty |
BindingFlags.Static | BindingFlags.FlattenHierarchy) where field.FieldType == typeof(DependencyProperty) let dp = (DependencyProperty)field.GetValue(null) where BindingOperations.IsDataBound(element, dp) let bindingExpression = BindingOperations.GetBindingExpression(element, dp) where boundType == bindingExpression.DataItem.GetType() where boundPropertyName == bindingExpression.ParentBinding.Path.Path select new ValidationBindingContext(bindingExpression, element as UIElement); if (result.FirstOrDefault() != null) return result.FirstOrDefault(); else { // Not found so check all child elements ValidationBindingContext bindingContext = GetBindingForProperty(boundType, boundPropertyName, element); if (bindingContext != null) return bindingContext; } } return null; }

But no – it was still going to suck, the performance would be horrible and the whole thing just looks so… “kludgy”. So, resigned I look on the net – horrified to find that the reflection method was one of two ways developers had commonly resorted to. The other method is to make use of the MarkupWriter class – which to me looked even worse .

It works…

Discovering WPF Bindings

…but does someone know a better way?

5 thoughts on “How to get a list of Bindings in WPF?”

  1. Hi Nigel,

    Didn’t have time to fully test this but you could use TypeDescriptor and DependencyPropertyDescriptor to write something like this:

    Button b = _button;
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(b);

    var results = from prop in props.Cast()
    let dependencyDescriptor = DependencyPropertyDescriptor.FromProperty(prop)
    where BindingOperations.IsDataBound(b, dependencyDescriptor.DependencyProperty)
    let bindingExpression = BindingOperations.GetBindingExpression(b, dependencyDescriptor.DependencyProperty)
    select new { Expression = bindingExpression, Element = b, Property = dependencyDescriptor.DependencyProperty };
    foreach (var result in results)
    Console.WriteLine(“Element {0} has binding expression {1} on property {2}”,

    However I believe it will only give you properties defined on the object itself (not attached dependency properties you have set on the object).

  2. Not sure if this meets your requirment? I found the most efficient way was to use create my own binding mark-up extension that wraps the wpf Binding class.
    This way, base on any event, you can perform any action you want without having to iterate through anything.″>

  3. Still not optimal but the LocalValueEnumerator mthod might me be more efficient than reflecting through fields.
    internal static class WPFHelper
    internal static void ActionAllBindings(FrameworkElement targetElement, Action action)
    WalkElementTree(targetElement, action);

    private static void WalkElementTree(object obj, Action action)
    FrameworkElement dependencyObject = obj as FrameworkElement;
    // Sometimes leaf nodes aren’t DependencyObjects (e.g. strings)
    if (dependencyObject == null)
    // Recursive call for each logical child
    AcionBindings(dependencyObject, action);
    foreach (object child in LogicalTreeHelper.GetChildren(dependencyObject))
    WalkElementTree(child, action);

    private static void AcionBindings(FrameworkElement target, Action action)
    LocalValueEnumerator localValueEnumerator = target.GetLocalValueEnumerator();
    while (localValueEnumerator.MoveNext())
    LocalValueEntry current = localValueEnumerator.Current;
    Binding binding = BindingOperations.GetBinding(target, current.Property);

    if (binding != null)


  4. Simon,

    Thanks a lot for your comments. I had seen the GetLocalValues but I was concerned that it wouldn’t work if the dependency property was set to its default value. Having said that I didn’t actually try it.

    I’d also considered your other approach of overriding Binding. In fact that’s what I’d already done because as you point out it lets me do a whole host of “other” things, in addition to allowing me to build a cached list of bindings that I can later refer to.

    I’m about to do a couple of posts of how this ties in with my own Validation Engine that tries to satisfy the requirements I posted about back in October 2007. I’d be interested to know whether you make use of IDataErrorInfo and/or the Validation.ErrorTemplate. I’ve put off looking at the implementation of the various Validation frameworks on codeplex because my work is primarily intended as a learning exercise for me in WPF and I wanted to nut as much out by myself. However, once I’ve got a working version I think I’ll definitely take the time to browse the more complete solutions that others like yourself have already made available.


  5. yep. the wpf validation binding make use of IDataErrorInfo and ErrorTemplate.

    For getting an error for a property it tries the following in order
    -try to get the errors from IDataErrorInfo
    -try to get the errors from rules (defined in xml or attributes) that decorate a property. looks like this
    [RequiredStringRule(InitialValue = “aaa”, IgnoreCase = true, TrimWhiteSpace = false)]
    public string FirstName

    You get to define a IErrorDisplayStrategy.
    public interface IErrorDisplayStrategy
    bool CanDisplayForElement(FrameworkElement);
    void DisplayError(BindingExpressionBase, FrameworkElement, errorMessage);
    void ClearError(FrameworkElement);
    there is a default IErrorDisplayStrategy that simply displays whatever ErrorTemplate is defined for the given FrameworkElement. Or, alternatively, you can remove the default IErrorDisplayStrategy and replace it with your own.

    The ErrorDisplayStrategy approach is inspired by some of Paul Stovells work.

Comments are closed.