问题
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;
and in the constructor
public MainTabPageViewModel(IToolbarItemBadgeService toolbarItemBadge)
{
_toolbarItemBadge = toolbarItemBadge;
_toolbarItemBadge.SetBadge(MainTabPage.Main,MainTabPage.Main.ToolbarItems.FirstOrDefault() , $"{BaseService.CartCounter}", Color.Orange, Color.White);
}
Exception is thrown :
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.
回答1:
From exception you can see that your service is not registred and it can not be resolved.
You will need to register your IToolbarItemBadgeService
interface, with implemenation inside of App.cs
in RegisterTypes
method.
Something like this:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IToolbarItemBadgeService, ToolbarItemBadgeService>();
// .. Other registration code
}
After this, you will be able to use IToolbarItemBadgeService
which is injected in your MainTabPageViewModel
.
Wishing you lots of luck with coding!
来源:https://stackoverflow.com/questions/50965277/how-to-access-toolbar-items-from-viewmodel-xamarin-forms