How can I find all the target Dependency Properties bound to a Property?
For example:
<UserControl>
开发者_如何学编程 <TextBox Text="{Binding Path=Foo, Mode=TwoWays}"/>
<TextBlock Text="{Binding Path=Foo}"/>
</UserControl>
In code, is it possible to find a list of dependency properties that uses the Foo property as the source?
It depends really and, as H.B. points out, but it would be very intensive even in the "easy" cases.
In your example, assuming you can get at the Bindings, you can check the Path property and see if it references your "Foo" property. But there are cases, where that would not work. A binding like {Binding Path=DataContext.Foo}
for example. Path's can be much more complex then single property names.
In addition, the DataContext can change depending on where you are. Elements defined in a DataTemplate do not inherit their parents data context by default. So if you had:
<UserControl>
<ContextControl Content="Test">
<ContextControl.ContentTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Foo, Mode=TwoWay}"/>
</DataTemplate>
</ContextControl.ContentTemplate>
</ContextControl>
</UserControl>
Then the Foo
property refers to the the string "Test"
not your object. There is also the case where the Source, ElementName, and RelativeSource properties are used on the Binding.
Assuming that you only have a single DataContext and only use single word paths, then you could probably find most, if not all, the targets.
First, you'd need to iterate over every element in the visual and logical trees VisualTreeHelper to traverse the visual tree. The logical tree would be tricker.
For each element, you'd have to iterate over every dependency property defined. For this you'd have to use reflection to the the public static fields of type DependencyProperty.
Next, for each dependency property you'd have to call GetBindingExpression to get the associated BindingExpression. Then you can get the parent binding using the ParentBinding property.
Then it's a simple matter of comparing the path property.
Yes, and for all i know you need to use reflection and it is also not a good idea in terms of performance.
精彩评论