如何从ViewModel Xamarin表单访问工具栏项 [英] How to access toolbar items from ViewModel Xamarin forms
问题描述
我尝试在 viewmodel 的工具栏项中设置填充
我有一个名为IToolbarItemBadgeService
I tried to set padge in toolbar item from viewmodel
I have interface called IToolbarItemBadgeService
public interface IToolbarItemBadgeService
{
void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor);
}
我想在工具栏项中设置徽章,我在注册界面后使用了此代码,但是会引发异常
I want to set badge in toolbar item i used this code after i Register the interface but it throw exception
private IToolbarItemBadgeService _toolbarItemBadge;
和构造函数
public MainTabPageViewModel(IToolbarItemBadgeService toolbarItemBadge)
{
_toolbarItemBadge = toolbarItemBadge;
_toolbarItemBadge.SetBadge(MainTabPage.Main,MainTabPage.Main.ToolbarItems.FirstOrDefault() , $"{BaseService.CartCounter}", Color.Orange, Color.White);
}
抛出
异常:
Unity.Exceptions.ResolutionFailedException:解决方法 依赖关系失败,类型='System.Object',名称='MainTabPage'. 发生以下异常:调用构造函数 LGMobileApp.Views.MainTabPage().例外是: ResolutionFailedException-解决依赖关系失败,键入 ='LGMobileApp.ViewModels.MainTabPageViewModel',名称='(无)'.发生以下异常:调用构造函数 LGMobileApp.ViewModels.MainTabPageViewModel(Prism.Navigation.INavigationService navigationService,LGMobileApp.Helpers.IToolbarItemBadgeService toolbarItemBadge).异常是:NullReferenceException-对象 引用未设置为对象的实例.
Unity.Exceptions.ResolutionFailedException: Resolution of the dependency failed, type = 'System.Object', name = 'MainTabPage'. Exception occurred while: Calling constructor LGMobileApp.Views.MainTabPage(). Exception is: ResolutionFailedException - Resolution of the dependency failed, type = 'LGMobileApp.ViewModels.MainTabPageViewModel', name = '(none)'. Exception occurred while: Calling constructor LGMobileApp.ViewModels.MainTabPageViewModel(Prism.Navigation.INavigationService navigationService, LGMobileApp.Helpers.IToolbarItemBadgeService toolbarItemBadge). Exception is: NullReferenceException - Object reference not set to an instance of an object.
推荐答案
从异常中您可以看到您的服务未注册且无法解析.
From exception you can see that your service is not registred and it can not be resolved.
您需要注册IToolbarItemBadgeService
接口,并在RegisterTypes
方法中的App.cs
内部实现.
You will need to register your IToolbarItemBadgeService
interface, with implemenation inside of App.cs
in RegisterTypes
method.
类似这样的东西:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IToolbarItemBadgeService, ToolbarItemBadgeService>();
// .. Other registration code
}
此后,您将能够使用注入到MainTabPageViewModel
中的IToolbarItemBadgeService
.
After this, you will be able to use IToolbarItemBadgeService
which is injected in your MainTabPageViewModel
.
祝您编程愉快!
这篇关于如何从ViewModel Xamarin表单访问工具栏项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!