You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms:如何从XAML绑定信息获取对应属性的PropertyInfo?

获取XAML绑定命令对应的PropertyInfo方法

可行,你可以通过以下步骤实现:

  • 第一步:从ToolbarItem获取Command属性的绑定表达式
    使用GetBinding方法获取指定属性的绑定对象:

    var commandBinding = ThisItem.GetBinding(ToolbarItem.CommandProperty);
    
  • 第二步:解析绑定路径得到目标属性名
    从绑定对象中提取XAML里定义的绑定属性名称:

    if (commandBinding?.Path != null)
    {
        var propertyName = commandBinding.Path.Path; // 这里会得到"SomeCommand"
    }
    
  • 第三步:通过反射获取ViewModel的PropertyInfo
    借助ViewModel的类型(或实例),使用反射获取对应属性的PropertyInfo:

    // 直接通过类型获取
    var viewModelType = typeof(MyNamespace.ViewModels.MyViewModel);
    var propertyInfo = viewModelType.GetProperty(propertyName);
    
    // 或者从页面的BindingContext获取实例后再获取类型
    var viewModel = BindingContext as MyViewModel;
    var propertyInfoFromInstance = viewModel?.GetType().GetProperty(propertyName);
    

注意:如果绑定路径是嵌套结构(比如"ParentViewModel.SomeCommand"),需要额外拆分路径层级,逐层获取对应的PropertyInfo。

内容的提问来源于stack exchange,提问作者Bernd Morgeneyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:28:21