在 Silverlight(和其他基于 XAML 的技术)中,有一个名为 GetBindingExpression 的方法,它允许我们检查给定依赖属性上的绑定(bind)。该方法位于 FrameworkElement 上,因此每个控件都可以让我们访问绑定(bind)表达式。
例如:
var selectedItemBindingExpression = GetBindingExpression(SelectedItemProperty);
但是,Xamarin Forms 中似乎没有等效项。有没有办法从 Xamarin Forms 中的 BindableProperty 属性获取绑定(bind)表达式?
最佳答案
我认为 Xamarin.Forms
中没有任何公共(public) API 可用于访问 BindingExpression
- 但您可以使用反射来访问关联的 绑定(bind)
和 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);
}
}
示例用法 - 获取绑定(bind)表达式
var expr = this.GetBinding(TextProperty).GetBindingExpression();
示例用法 - 获取绑定(bind)路径(更新 07/27)
//to access path - you can directly use the binding object
var binding = this.GetBinding(TextProperty);
var path = binding?.Path;
关于c# - Xamarin 表单 - GetBindingExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45340019/