How to access toolbar items from ViewModel Xamarin forms

老子叫甜甜 提交于 2019-12-13 04:01:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!