MVVM : how to pass parameter to ViewModel's constructor

Yeonho picture Yeonho · Nov 8, 2010 · Viewed 19.9k times · Source

I'm using L. Bugnion's MVVM Light Framework.
What are some of the recommended approaches to pass parameters such as Customer's ID to ViewModel's constructor?

Edit: The parameter I need for each ViewModel is not something that is shared across models. it is something unique to each viewmodel instance.

Answer

Jgraham picture Jgraham · Apr 4, 2011
//Create a container class to pass via messenger service
    public class CarSelectedArgs
    {
      #region Declarations

      public Car Car { get; set; }

      #endregion

      #region Constructor

      public CarSelectedArgs(Car car)
      {
        Car = car;
      }

      #endregion
    }


    //example of view model sending message.
    public class SendingViewModel : ViewModelBase
    {
      private Car _car;
      public Car SelectedCar
      {
        get { return _car; }
        set
        {
          _car = value;
          if (value != null)
          {
            //messenger will notify all classes that have registered for a message of this type
            Messenger.Default.Send(new CarSelectedArgs(value));
          }
        }
      }
    }


    //Example of ViewModel registering to recieve a message
    public class SampleViewModel : ViewModelBase
    {
      #region Constructor

      public SampleViewModel()
      {
        Messenger.Default.Register<CarSelectedArgs>(this, OnCarSelected);
      }
      #endregion

      #region LocalMethods

      void OnCarSelected(CarSelectedArgs e)
      {

        var NewCar = e.Car;
      }

      #endregion
    }