我有一个类利用新的 Xamarin Forms Shell 搜索来填充搜索栏的项目源我想使用我的存储库来获取项目列表。
使用 Prism MVVM 框架我宁愿使用 DI 而不是自己创建一个新实例。但是,这样做时,我的代码无法编译,因为 XAML 代码中引用的搜索处理程序提示没有无参数构造函数。有解决办法吗?或者,还有更好的方法?请让我知道
搜索处理程序类(我希望它是怎样的)
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>
最佳答案
我要做的是完全删除 IngredientsSearchHandler
并将常规 SearchHandler
的 Query
和 ItemsSource
绑定(bind)到属性在 View 模型上并对查询的更改使用react那里(通过更新ItemsSource
)。
View 模型会自动注入(inject)其依赖项(因为您使用了 ViewModelLocator
),而且我不知道有什么方法可以拦截 xaml 中定义的控件的创建以使用容器。
关于c# - 使用 XAML 进行依赖注入(inject),这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57046730/