使用 XAML 的依赖注入,可能吗?

Dependency Injection with XAML, is it possible?

我有一个 class,它利用了新的 Xamarin Forms Shell 搜索,以填充搜索栏的项目源 我想使用我的存储库来获取项目列表.

使用 Prism MVVM 框架我宁愿使用 DI 而不是自己创建一个新实例。但是,这样做时,我的代码无法编译,因为 XAML 代码中引用的搜索处理程序抱怨没有无参数构造函数。有解决办法吗?或者,还有更好的方法?请告诉我

搜索处理程序class(我想要的样子)

public class IngredientsSearchHandler : SearchHandler
    {
        private readonly IUnitOfWork _unitOfWork;

        public IngredientsSearchHandler(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        protected override void OnQueryChanged(string oldValue, string newValue)
        {
            base.OnQueryChanged(oldValue, newValue);

            if (string.IsNullOrWhiteSpace(newValue))
            {
                ItemsSource = null;
            }
            else
            {
                ItemsSource = _unitOfWork.IngredientRepository.GetAll().Where(x => x.Name.ToLower().Contains(newValue.ToLower())).ToList();
            }
        }
    }

查看引用搜索处理程序的内容

错误是:“没有给定的参数对应于 'IngredientsSearchHandler.IngredientsSearchHandler(IUnitOfWork)' 的所需形式参数 'unitOfWork'”

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:controls="clr-namespace:TestApp.Controls"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             mc:Ignorable="d"
             x:Class="TestApp.Views.IngredientsView">

    <Shell.SearchHandler>
        <controls:IngredientsSearchHandler Placeholder="Enter ingredient.."
                                           ShowsResults="true"
                                           DisplayMemberName="Name"
                                           Keyboard="Text">
            <controls:IngredientsSearchHandler.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Label Text="{Binding Name}"
                               FontAttributes="Bold"/>
                    </Grid>
                </DataTemplate>
            </controls:IngredientsSearchHandler.ItemTemplate>
        </controls:IngredientsSearchHandler>
    </Shell.SearchHandler>

    <ContentPage.Content>
            <Label Text="Test"/>
    </ContentPage.Content>
</ContentPage>

简而言之,您可以在 XAML 中将 DependencyInjection 与 ContainerProvider 一起使用。

<ContentPage xmlns:prism="http://prismlibrary.com"
             xmlns:converters="using:MyProject.Converters">
  <ContentPage.Resources>
    <prism:ContainerProvider x:TypeArguments="converters:SomeConverter" x:Key="someConverter" />
  </ContentPage.Resources>
</ContentPage>

我要做的是完全删除 IngredientsSearchHandler 并将常规 SearchHandlerQueryItemsSource 绑定到视图模型上的属性并对查询那里(通过更新ItemsSource)。

视图模型会自动注入其依赖项(因为您使用 ViewModelLocator),我不知道有什么方法可以拦截 xaml 中定义的控件的创建以使用容器。