ClarkG
ClarkG

Reputation: 81

How to receive messages in a .Net 6 static class using the Community Toolkit Messenger

I'm using the Microsoft Community Toolkit's default Messenger to send messages between modules in my program and it works great - until I try to receive a message in a static class.

I've been struggling through the Microsoft Learn pages about Messenger and Register, but I don't know enough to be able to follow the descriptions. (These particular pages seem to be written by experts for experts, and I'm not expert (or smart) enough to figure out what they are talking about.)

My question is: Can a static class receive messages (seems very likely), and if so, what syntax do I have to use to register? It must be some variation of the last example above, but I haven't yet been able to figure out what it would be.

Thanks.

Upvotes: 0

Views: 403

Answers (2)

Markus
Markus

Reputation: 4577

iStuart's answer is actually exactly right. If you like it a bit more complete, here is a short example:

static void YourStaticMethod()
{
    WeakReferenceMessenger.Default.Register<MyMessage>(typeof(classname), (recipient, message) =>
    {
        // handle message here...
    });
}

instead of:

static void YourStaticMethod()
{
    WeakReferenceMessenger.Default.Register<MyMessage>(this, (recipient, message) =>
    {
        // handle message here...
    });
}

So you only have to replace "this" with "typeof(classname)".

Upvotes: 0

iStuart
iStuart

Reputation: 425

I've just started to change my app from using event and EventHandler to WeakReferenceMessenger and encountered the same situation with a static class. My solution is to use

typeof(classname), (r, m) =>

instead of

this, (r, m) =>

and the lambda is called as expected.

A similar solution is to define a variable called me at the top of the class as as:

private static readonly Type me = typeof(classname);

then use

me, (r, m) =>

Upvotes: 0

Related Questions