-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathMessengerPageViewModel.cs
More file actions
89 lines (72 loc) · 2.7 KB
/
MessengerPageViewModel.cs
File metadata and controls
89 lines (72 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Messaging;
using Microsoft.Toolkit.Mvvm.Messaging.Messages;
namespace MvvmSample.ViewModels
{
public class MessengerPageViewModel : SamplePageViewModel
{
public UserSenderViewModel SenderViewModel { get; } = new UserSenderViewModel();
public UserReceiverViewModel ReceiverViewModel { get; } = new UserReceiverViewModel();
// Simple viewmodel for a module sending a username message
public class UserSenderViewModel : ObservableRecipient
{
private string username = "Bob";
public string Username
{
get => username;
private set => SetProperty(ref username, value);
}
protected override void OnActivated()
{
Messenger.Register<CurrentUsernameRequestMessage>(this, (r, m) => m.Reply(Username));
}
public void SendUserMessage()
{
Username = Username == "Bob" ? "Alice" : "Bob";
Messenger.Send(new UsernameChangedMessage(Username));
}
}
// Simple viewmodel for a module receiving a username message
public class UserReceiverViewModel : ObservableRecipient
{
private string username = "";
public string Username
{
get => username;
private set => SetProperty(ref username, value);
}
protected override void OnActivated()
{
Messenger.Register<UsernameChangedMessage>(this, (r, m) => Username = m.Value);
}
}
private string username;
public string Username
{
get => username;
private set => SetProperty(ref username, value);
}
public void RequestCurrentUsername()
{
Username = WeakReferenceMessenger.Default.Send<CurrentUsernameRequestMessage>();
}
public void ResetCurrentUsername()
{
Username = null;
}
// A sample message with a username value
public sealed class UsernameChangedMessage : ValueChangedMessage<string>
{
public UsernameChangedMessage(string value) : base(value)
{
}
}
// A sample request message to get the current username
public sealed class CurrentUsernameRequestMessage : RequestMessage<string>
{
}
}
}