[FIXED] Is there any advantage or disadvantage in using a Xamarin.Forms MessagingCenter to communicate between a ViewModel and methods

Issue

I am looking into using one or other method and in particular method 2. Can anyone tell me the advantages and disadavantages of using the 2nd method over the 1st.

Method 1 – ViewModel.cs

PTBtnCmd = new Command<Templates.WideButton>((btn) =>             
              MessagingCenter.Send<CFSPageViewModel, Templates.WideButton>(
              this, "PTBtn", btn));

Method 1 – MyPage.xaml.cs (SetLang etc.. methods in this file )

MessagingCenter.Subscribe<CFSPageViewModel, Templates.WideButton>(
        this, "PTBtn", (s, btn) =>
        {
            Utils.SetState(btn.Text, vm.PT);
            SetLangVisible(btn.Text);
            SetLangSelected(btn.Text);
            vm.CFSMessage = Settings.cfs.TextLongDescription();
        });

or

Method 2 – ViewModel.cs (SetLang etc.. methods in this file )

PTBtnCmd = new Command<string>(SetMode);

private void SetMode(string btnText)
    {
        Utils.SetState(btnText, PT);
        SetLangVisible(btnText);
        SetLangSelected(btnText);
        CFSMessage = Settings.cfs.TextLongDescription();
    }

Would also like to hear comments on the idea of adding methods into the ViewModel.cs code. Would it be better for these to be in another file?

Solution

I would not use the messaging in the VM layer because your VM layer can then only be used in Xamarin.Forms. Some Mvm frameworks, like mvvmlight, offer a messaging capability. I would opt for that instead as you could then reuse your VMs in Wpf, Uwp or other UI frameworks other than XF.

Also i wouldn’t use the messaging like you have. If probably just use databinding and raise PropertyChanged events in the VM which the view can react to.

Answered By – Andy

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published