c# - Xamarin 表单 - GetBindingExpression

标签 c# wpf silverlight xamarin.forms

在 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/

相关文章:

wpf - 在静态方法中使用 WPF 检测设计模式

c# - 为什么当我执行 BeginGetRequestStream 时会收到 ProtocolViolationException

c# - 获取浏览器中打开的标签页的 URL

c# - IoC/DI 框架与智能客户端 Winform 应用程序 : How should I approach this?

c# - 使用 Task.Run 而不是 Delegate.BeginInvoke

silverlight - 白银图表轴间隔

silverlight - 从 Outlook 拖放到 Silverlight 应用程序

c# - 非线性系统 - 如何跟踪委托(delegate)的未知数?

c# - 在 WPF 中重新加载绑定(bind)到 Datagrid 的 DataTable

c# - 更新绑定(bind)到自定义类属性的组合框条目的最佳方法