Any ideas on how to implement a method that given a propertyname, finds a control (perhaps from a visualtree) which is bound to the given property?
Try this one. First, copy-paste this DependencyObjectHelper class in your project. It has a function that allows you to get all the BindingObjects in a given object.
public static class DependencyObjectHelper
{
public static List GetBindingObjects(Object element)
{
List bindings = new List();
List dpList = new List();
dpList.AddRange(DependencyObjectHelper.GetDependencyProperties(element));
dpList.AddRange(DependencyObjectHelper.GetAttachedProperties(element));
foreach (DependencyProperty dp in dpList)
{
BindingBase b = BindingOperations.GetBindingBase(element as DependencyObject, dp);
if (b != null)
{
bindings.Add(b);
}
}
return bindings;
}
public static List GetDependencyProperties(Object element)
{
List properties = new List();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.DependencyProperty != null)
{
properties.Add(mp.DependencyProperty);
}
}
}
return properties;
}
public static List GetAttachedProperties(Object element)
{
List attachedProperties = new List();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.IsAttached)
{
attachedProperties.Add(mp.DependencyProperty);
}
}
}
return attachedProperties;
}
}
Then, create this GetBindingSourcesRecursive function. It recursively collects the DependencyObjects in the visual tree that has at least one Binding object targetting a given property name.
private void GetBindingSourcesRecursive(string propertyName, DependencyObject root, List
Then, to use this, just call GetBindingsRecursive passing in the property name, the root visual (e.g. the Window), and an object list that will contain the results.
List
Hope this helps.