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

如何在Xamarin.Forms中通过Caliburn.Micro注入ILicenseInfo集合?

在Caliburn.Micro + Xamarin.Forms中注入IEnumerable集合

嘿,这个问题我之前也碰到过!Caliburn.Micro的SimpleContainer默认不会自动把单个注册的服务转换为集合类型,所以我们需要手动告诉容器怎么解析IEnumerable<ILicenseInfo>。下面分步骤来解决:

1. 修改App.cs中的容器注册

在你现有的PerRequest注册之后,添加一个自定义的注册处理器,让容器知道如何生成IEnumerable<ILicenseInfo>实例。根据你的需求,有两种常见的实现方式:

方式一:返回固定数量的实例

如果需要生成多个LicenseInfoImplementation实例,直接在处理器里调用容器的GetInstance方法多次即可:

public partial class App : FormsApplication 
{ 
    private readonly SimpleContainer _container; 
    public App (SimpleContainer container) 
    { 
        InitializeComponent(); 
        this._container = container; 

        // 注册单个ILicenseInfo实例
        _container.PerRequest<ILicenseInfo, LicenseInfoImplementation>(); 

        // 注册IEnumerable<ILicenseInfo>的解析逻辑
        _container.RegisterHandler<IEnumerable<ILicenseInfo>>(container => 
        {
            // 这里可以根据需求创建任意数量的实例
            return new List<ILicenseInfo>
            {
                container.GetInstance<ILicenseInfo>(),
                container.GetInstance<ILicenseInfo>(),
                // 可继续添加更多,或从数据源动态加载实例
            };
        });
    } 
}

方式二:自动获取所有注册的ILicenseInfo实现

如果你以后可能会添加其他ILicenseInfo的实现类,这种方式更灵活,它会自动收集所有注册的ILicenseInfo类型实例:

_container.RegisterHandler<IEnumerable<ILicenseInfo>>(container => 
{
    return container.GetAllInstances<ILicenseInfo>();
});

注意:如果只有LicenseInfoImplementation这一个实现,GetAllInstances会返回包含一个该类实例的集合;如果注册了多个实现类,会返回所有对应的实例。

2. ViewModelTwo的处理

你的ViewModelTwo构造函数已经写对了,只需补充一个可绑定的属性供XAML使用即可:

public ViewModelTwo(IEnumerable<ILicenseInfo> licenses) 
{ 
    // 保存注入的集合,并转换为可绑定的ObservableCollection
    Licenses = new ObservableCollection<ILicenseInfo>(licenses);
}

// 暴露公共属性,用于XAML绑定
public ObservableCollection<ILicenseInfo> Licenses { get; }

3. ViewModelTwo对应的XAML(ViewModelTwoView.xaml)

XAML部分只需遵循Caliburn.Micro的命名约定(ViewModel名称+View,比如ViewModelTwo对应ViewModelTwoView),并把集合绑定到UI控件即可。比如用ListView展示所有License信息:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourNamespace.Views.ViewModelTwoView">
    <StackLayout>
        <ListView ItemsSource="{Binding Licenses}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding YourLicenseProperty}" />
                    <!-- 替换成你LicenseInfoImplementation中的实际属性 -->
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

内容的提问来源于stack exchange,提问作者Mouse On Mars

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:18:01