Melbourne Developer Melbourne Developer - 1 year ago 137
C# Question

Xamarin Forms - GetBindingExpression

In Silverlight (and other XAML based technologies) there is a method called GetBindingExpression which allows us to check what binding there is on a given dependency property. The method is on FrameworkElement so every single control gives us access to the binding expression.

For example:

var selectedItemBindingExpression = GetBindingExpression(SelectedItemProperty);


But, there doesn't seem to be an equivalent in Xamarin Forms. Is there a way to get a binding expression from a BindableProperty property in Xamarin Forms?

Answer Source

I don't believe there are any public APIs available in Xamarin.Forms to access to the BindingExpression - but you can use reflection to access the associated Binding and thus the BindingExpression

public static class BindingObjectExtensions
{
    public static Binding GetBinding(this BindableObject self, BindableProperty property)
    {
        var methodInfo = typeof(BindableObject).GetTypeInfo().GetDeclaredMethod("GetContext");
        var context = methodInfo?.Invoke(self, new[] { property });

        var propertyInfo = context?.GetType().GetTypeInfo().GetDeclaredField("Binding");
        return propertyInfo?.GetValue(context) as Binding;
    }

    public static object GetBindingExpression(this Binding self)
    {
        var fieldInfo = self?.GetType().GetTypeInfo().GetDeclaredField("_expression");
        return fieldInfo?.GetValue(self);
    }
}

Sample usage

var expr = this.GetBinding(TextProperty).GetBindingExpression();

Sample usage 2 (update 07/27)

//to access path - you can directly use the binding object
var binding = this.GetBinding(TextProperty);
var path = binding?.Path;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download