I'm trying to translate this XAML code:
<Binding Path="DataContext" RelativeSource="{RelativeSource AncestorType={x:Type UserControl}}" />
Into this C# code:
var binding = new Binding("DataContext")
{
RelativeSource = new RelativeSource {AncestorType = typeof(UserControl)}
};
var value = PropertyPathHelper.GetValue(binding);
The implementation of my PropertyPathHelper (modified from another thread) class is as follows:
public static class PropertyPathHelper
{
public static object GetValue(Binding binding)
{
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
return _dummy.GetValue(Dummy.ValueProperty);
}
private static readonly Dummy _dummy = new Dummy();
private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
}
}
Either my Binding declaration isn't right, or my PropertyPathHelper implementation isn't right, but I don't know which, because at runtime, "var value" comes out as null. Even if I pass a non-existent name into the constructor of Binding.
The binding works fine if I do it in XAML, but I have to do it in the codebehind. In case it's not clear, I'm trying to get the actual value of the DataContext of this view's first ancestor, which is of type UserControl.
What am I doing wrong?