How to establish communication/pass data between two ViewModels

后端 未结 1 860
余生分开走
余生分开走 2021-01-02 20:23

I\'m aware this question has already been asked numerous times, and I\'ve read many answers referring to it. Nevertheless, none of them fulfilled my requirements, and hence

相关标签:
1条回答
  • 2021-01-02 20:37

    Personally I would go with option 3.

    The messaging mechanism keeps your viewmodels separated from each other and once you work through one example, you'll see it is quite easy.

    Personally I like to add a message broker class with static methods for each message type I want to send, this helps me centralise changes - but essentially you've got a send and receive. You can send what you want and if something wants to receive it they can.

    MVVM Light is a great framework for this.

    Send:

    GalaSoft.MvvmLight.Messaging.Messenger.Send<LoginSuccessMessage>(new LoginSuccessMessage() { UserName = user });
    

    Receive, in my target View Model constructor:

    this.MessengerInstance.Register<LoginSuccessMessage>(this, this.OnLoginSuccessMessage);
    

    Handler in the target View Model:

        private async void OnLoginSuccessMessage(LoginSuccessMessage message)
        {
            this.CurrentUserName = message.UserName;
            this.MoveToState(ApplicationViewModelState.Active);
    
            await Task.Delay(5000);
            this.MoveToState(ApplicationViewModelState.Idle);
        }
    

    In this example, I am sending a user ID as a property on the message class:

    public class LoginSuccessMessage : MessageBase
    {
    
        private string _UserName;
    
        public string UserName
        {
            get
            {
                return this._UserName;
            }
    
            set
            {
                this._UserName = value;
            }
        }
    }
    

    Replace that property with whatever you want be that a collection or complex object.

    0 讨论(0)
提交回复
热议问题