Prism之EventAggregator——实现ViewModel之间传递数据的工作

public class MessageViewModel : BindableBase
{
    IEventAggregator _ea;

    private string _message = "Message to Send";
    public string Message
    {
        get { return _message; }
        set { SetProperty(ref _message, value); }
    }

    public DelegateCommand SendMessageCommand { get; private set; }

    public MessageViewModel(IEventAggregator ea)
    {
        _ea = ea;
        SendMessageCommand = new DelegateCommand(SendMessage);
    }
    private void SendMessage()
    {
        _ea.GetEvent<MessageSentEvent>().Publish(Message);
    }
}
public class MessageListViewModel : BindableBase
{
    IEventAggregator _ea;

    private ObservableCollection<string> _messages;
    public ObservableCollection<string> Messages
    {
        get { return _messages; }
        set { SetProperty(ref _messages, value); }
    }

    public MessageListViewModel(IEventAggregator ea)
    {
        _ea = ea;
        Messages = new ObservableCollection<string>();

        _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived);
    }

    private void MessageReceived(string message)
    {
        Messages.Add(message);
    }
}
posted @ 2024-06-07 17:45  回首起了风沙  Views(12)  Comments(0Edit  收藏  举报