【发布时间】:2012-11-12 21:34:03
【问题描述】:
我有一个奇怪的问题。
我正在使用 GalaSoft 的 MVVM Light 框架,到目前为止一切正常。 在我尝试执行以下操作之前,我正在使用信使系统在 ViewModel 之间发送消息:
我有一个发送消息的单例类 GateKeeper。
此类不是 ViewModel,因此不继承自 ViewModelBase。
如果它发送一条消息,它不会在任何地方收到。
我尝试了以下方法:
- 让
GateKeeper继承自ViewModeBase-> 没有成功。 - 注册
GateKeeper以接收消息,从而查看它是否会捕获/接收实际从自身发送的消息 -> 不成功。 - 将
GateKeeper从 Singleton 更改为正常实例化 -> 没有成功 - 创建一个未连接到视图的 MVVM ViewModel,并让它发送消息,就像
GateKeeper-> no Success
我所有连接到视图的视图模型都可以发送消息,并且它们将被接收。
在信使工作之前,似乎必须将视图模型“链接”到视图,但 imo。这是一个主要限制。
以下是当前非常简化的设置。
在 GateKeeper 上调用 ApplicationInitialize 不会触发主视图模型或 GateKeeper 类本身收到的消息。
希望有人对这个问题提出建议。
谢谢..
示例设置: MainViewModel 构造函数:
public MainViewModel()
{
Messenger.Default.Register<LoadViewMessage>(this, (message) =>
{
if (message.Sender is GateKeeper) CurrentView = message.View;
else if (message.Sender is LoginViewModel) CurrentView = message.View;
else if (message.Sender is MenuItemBarViewModel) CurrentView = message.View;
});
看门人:
public class GateKeeper : IGateKeeper
{
private readonly IEmployeeService _employeeService;
#region Implementation of IGateKeeper
public void ApplicationInitialize()
{
Messenger.Default.Send<LoadViewMessage>(new LoadViewMessage(ObjectLocator.MainMapView), this);
}
public void LoginSucceeded(Employee employee)
{
//This is where we retrieve the available services for the current employee
//TODO: add methods for retrieving service info from backend
//Send a message that should make the mainview load the map into its currentview property
Messenger.Default.Send(new LoadViewMessage(ObjectLocator.MainMapView), this);
}
#endregion
public GateKeeper(IEmployeeService employeeService)
{
_employeeService = employeeService;
//Test.. Is not triggered
//Just used for debugging, thus nothing happens inhere.
Messenger.Default.Register<LoadViewMessage>(this, (message) =>
{
if (message.Sender is GateKeeper) ;
else if (message.Sender is LoginViewModel) ;
else if (message.Sender is MenuItemBarViewModel);
});
}
消息类:LoadViewMessage
public class LoadViewMessage : MessageBase
{
public UserControl View { get; protected set; }
public LoadViewMessage(UserControl view, object sender): base(sender)
{
View = view;
}
public LoadViewMessage(UserControl view):this(view, null){}
}
PS:ObjectLocator 是一个 NinJect 类,用于处理对象的所有实例化及其生命周期
@更新 LBugnion(MVVM Light 的创建者)指出问题出在 send 方法上,我实际上是在使用带有令牌的 Send 重载。
@这在我的情况下不起作用
Messenger.Default.Send(new LoadViewMessage(ObjectLocator.MainMapView), this);
@这会起作用
Messenger.Default.Send(new LoadViewMessage(ObjectLocator.MainMapView, this));
this 应该作为 token
传递给 loadViewMessage 而不是 Send 方法【问题讨论】:
-
我不知道为什么您的代码不起作用,但我可以告诉您它应该。消息传递系统不依赖于 ViewModel/View 关系。
-
你调试过(断点)
GateKeeper方法吗?例如,您使用的是非默认构造函数(带参数),它被调用了吗? -
非常。它应该可以工作,并且当我在视图中使用的其他视图模型中使用它时也可以。我已经调试了所有并调用了 GateKeeper 的构造函数。我不知道为什么它在这里不起作用。
标签: silverlight mvvm-light messaging