Let the ViewModel know the generic object of the View

白昼怎懂夜的黑 提交于 2019-12-04 20:46:57

In MVVM Light you would send a publisher/subscriber style broadcast message that would allow you to communicate with the "hosting" view model without having to have a hard reference to the "hosting" control in the "hosted" control.

This allows the "hosted" control to stay decoupled from the "hosting" control and yet communicate with between the two.

EDIT:

In MVVM Light there's a messenger object that takes care of a lot of the details for you. You can create message classes that keep different messages and the arguments they send seperate. You can also specify a "Token" just a specific string (I usualy setup a set of constants in a class to house my various "Tokens") that allows only the subsribers to that message and that token to receive the message. I've included a code sample below of what I use in MVVM Light in v3 of MVVM Light you need to make sure to unregister from the message because it does not use the weak eventing pattern.

If you didn't want to use MVVM Light you can use the same idea in your publisher/subscriber model, you'd just have to do the work on determining if the token the publisher sent is the token the subscriber is looking for on your own

public static class DescriptiveMessageName
{
public static void Send(object args)
{
    Messenger.Default.Send(args, "SpecificToken");
}

public static void Send(object args, string token)
{
    Messenger.Default.Send(args, token);
}

public static void Register(object recipient, Action<object> action)
{
    Messenger.Default.Register(recipient,
              "SpecificToken", action);
}

public static void Register(object recipient, string token, Action<object> action)
{
    Messenger.Default.Register(recipient,
              token, action);
}

public static void UnRegister(object recipient)
{
    Messenger.Default.Unregister<object>(recipient);
}

public static void UnRegister(object recipient, Action<object> action)
{
    Messenger.Default.Unregister<object>(recipient, action);
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!