locked
How to get the information of changes from UserControl Viewmodel to Mainpage Viewmodel

    Question

  • Hi Everyone,

    I have a Page(Main Page) which is using couple of user controls. The data context of Main page is from Main View Model.

    Each user control has its respected view model.

    I want changes in user control's view model to be triggered in Main page View model.

    Please let me know how can this be achieved.

    Thanks in advance,

    Sunil Kumar


    Thanks and Regards Sunil Kumar S C

    Monday, November 24, 2014 11:55 AM

Answers

  • I think each of your user control's View Model would be part of main Page View Model. If so then I will use something like this:

    public class MainPageViewModel : BaseViewModel
    {
        private UserControl1ViewModel userControl1ViewModel;
    
        public UserControl1ViewModel UserControl1ViewModel
        {
            get { return userControl1ViewModel; }
            set { SetPropert(ref userControl1ViewModel, value); }
        }
    
        public MainPageViewModel()
        {
            userControl1ViewModel = new UserControl1ViewModel(handleControl1Change);
        }
    
        private void handleControl1Change(object args)
        {
            //Handle changes here
        }
    
    }
    
    public class UserControl1ViewModel : BaseViewModel
    {
        private Action<object> handleChange;
    
        public UserControl1ViewModel(Action<Object> handleChange)
        {
            this.handleChange = handleChange;
        }
    
        private void dummyMethod()
        {
            if (this.handleChange != null)
            {
                //I am passing this, but this could be anything
                this.handleChange(this);
            }
        }
    }

    If your ViewModels are not structured like this then I have also used BaseViewModel (base class for all view models) to have a (or set of) notifying properties that can be used.

    Best solution for such kind of problem will be a messaging infrastructure for ViewModels :) I am happy to put one up here if need be.


    -- Vishal Kaushik --

    Please 'Mark as Answer' if my post answers your question and 'Vote as Helpful' if it helps you. Happy Coding!!!

    Monday, November 24, 2014 7:01 PM