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

.NET MAUI XAML中如何将模型注解绑定到控件?

解决方案

1. 编写反射辅助工具类

创建静态类,通过反射读取模型属性的[Display]注解信息:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class AnnotationHelper
{
    // 获取指定属性的Display.Name
    public static string GetDisplayName<T>(string propertyName)
    {
        PropertyInfo? property = typeof(T).GetProperty(propertyName);
        if (property == null) return propertyName;

        DisplayAttribute? displayAttr = property.GetCustomAttribute<DisplayAttribute>();
        return displayAttr?.Name ?? propertyName;
    }

    // 获取指定属性的Display.Prompt
    public static string GetDisplayPrompt<T>(string propertyName)
    {
        PropertyInfo? property = typeof(T).GetProperty(propertyName);
        if (property == null) return string.Empty;

        DisplayAttribute? displayAttr = property.GetCustomAttribute<DisplayAttribute>();
        return displayAttr?.Prompt ?? string.Empty;
    }
}

2. 在ViewModel中实现绑定属性

基于CommunityToolkit.Mvvm的ObservableObject实现ViewModel,自动处理UI更新通知:

using CommunityToolkit.Mvvm.ComponentModel;

public class PersonViewModel : ObservableObject
{
    private Person _person = new Person();
    public Person Person
    {
        get => _person;
        set => SetProperty(ref _person, value);
    }

    // 绑定到Label的DisplayName
    public string NameDisplayName => AnnotationHelper.GetDisplayName<Person>(nameof(Person.Name));

    // 绑定到Entry的Placeholder
    public string NamePrompt => AnnotationHelper.GetDisplayPrompt<Person>(nameof(Person.Name));
}

3. 调整XAML绑定逻辑

替换原示例中的占位绑定,关联ViewModel的实际属性:

<StackLayout>
    <Label Text="{Binding NameDisplayName}"/>
    <Entry Text="{Binding Person.Name}" Placeholder="{Binding NamePrompt}"/>
</StackLayout>

补充配置

确保页面的BindingContext指向ViewModel实例,比如在页面后台代码中:

public PersonPage()
{
    InitializeComponent();
    BindingContext = new PersonViewModel();
}

如果需要支持模型动态切换,可将NameDisplayName和NamePrompt改为可通知属性,在Person实例变更时重新计算值并调用OnPropertyChanged方法触发UI更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:12:10