AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Thursday 20 October 2016

How to communicate between two View Models in MVVM?

In this article i am going to discuss communication between two View Models in MVVM. We can easily communicate between two view models using event handlers. Lets say I have two views(View1.xaml & View2.xaml ) these two views are associated with two ViewModels( View1ViewModel.cs & View2ViewModel.cs)  I want to send message from View1 to View2. 
Please check below implementation.

Step 1- Create Event Inside View 2

public class View2ViewModel:ViewModelBase
    {
        #region--Private Properties--
        private string title;
        #endregion

        #region Events
        public EventHandler Event1ExecutionHandler;
        #endregion

        #region--Instance--
        public View2ViewModel()
        {
            Event1ExecutionHandler += OnEvent1Execute;
        }

        private void OnEvent1Execute(object sender, EventArgs e)
        {
           string recivedstring= (string)sender;
            Title = recivedstring;
        }
        #endregion

        #region--Public Prooperties
        public string Title
        {
            get
            {
                return title;
            }
            set
            {
                title = value;
                OnPropertyChanged("Title");
            }

        }
        #endregion
    }
Inside View2ViewModel, I have created an event handler Event1ExecutionHandler & bind it with a method name OnEvent1Execute.

Step 2-Send Message to View2 by View1 via the handler


    public class View1ViewModel : ViewModelBase
    {

        #region--Constructor--
        public View1ViewModel()
        {

        }
        #endregion


        #region--Methods--
        private void ExecuteClickCommand(object obj)
        {
            View2ViewModel.Event1ExecutionHandler("Button is Clicked", null);
        }

        public ICommand ClickCommand
        {
            get { return new DelegateCommand(ExecuteClickCommand); }
        }
        #endregion
    }
As you click button in View1 Text will changed in View2

0 comments :

Post a Comment

  • Popular Posts
  • Comments