我有四个视图模型M1,M2,M3,M4,我将消息发送到另一个视图模型M5。当M5收到来自其中任何一个的消息时,它会执行相同的操作。目前,我已经在M5中编写了这样的代码:
MessgingCenter.Subscribe<M1, string>(this, "abc", () => { DoSomething(); });
MessagingCenter.Subscribe<M2, string>(this, "abc", () => { DoSomething(); });
MessgingCenter.Subscribe<M3, string>(this, "abc", () => { DoSomething(); });
MessagingCenter.Subscribe<M4, string>(this, "abc", () => { DoSomething(); });
我能用单线实现吗?
答案 0 :(得分:1)
您可以使用名称如“BaseViewModel”从同一父ViewModel(或接口)继承M1,M2,M3,M4,然后写入:
MessagingCenter.Subscribe<BaseViewModel, string>(this, "abc", () => { DoSomething(); });
答案 1 :(得分:1)
首选使用 hugo 的方法,但如果没有其他方法,您也可以简单地将订阅者变为string
。您只需要小心这样做,因为多个订阅者很容易从同一个发送中触发。
MessagingCenter.Subscribe<string>(this , "abc", somethingString => { DoSomething(somethingString); });
则...
MessagingCenter.Send("something", "abc");
编辑:添加hugo的答案中提到的界面代码示例:
public interface IDoSomething { } //Does not necessarily have to have anything in it
public class ViewModelA : IDoSomething { }
public class ViewModelB : IDoSomething { }
MessagingCenter.Subscribe<IDoSomething, string>(this, "abc", () => { DoSomething(); }); //IDoSomething works the same as deriving from a base class in this instance