在我使用Caliburn.micro框架学习MVVM之后......我正在尝试通过EventAggregator传递两个viewModels这样的代码(带有“无意义”的代码,仅用于测试):
MainWindowViewModel.cs
namespace TOP
{
[Export(typeof(MainWindowViewModel))]
public class MainWindowViewModel : Conductor<IScreen>.Collection.OneActive
{
readonly IWindowManager windowManager;
private readonly IEventAggregator events;
private bool _Logged;
[ImportingConstructor]
public MainWindowViewModel(IWindowManager windowManager, IEventAggregator events)
{
DisplayName = "TOP";
this.events = events;
events.Subscribe(this);
this.windowManager = windowManager;
windowManager.ShowDialog(new LoginViewModel(events));
}
public bool Logged
{
get { return _Logged; }
set
{
_Logged = value;
if(_Logged== true)
InitiateApp();
}
}
public void Handle(LoginEvent message)
{
Logged = message.Logged;
}
private void InitiateApp() {
ActivateItem(new TwoWindowViewModel());
}
}
}
LoginViewModel.cs
namespace TOP{
[Export(typeof(IScreen))]
public class LoginViewModel : Screen
{
private readonly IEventAggregator _events;
[ImportingConstructor]
public LoginViewModel(IEventAggregator events)
{
DisplayName = "Login";
_events = events;
Login();
}
public void Login()
{
_events.Publish(new LoginEvent(true));
}
}
}
LoginEvent.cs
namespace TOP
{
public class LoginEvent
{
public LoginEvent(bool logged)
{
Logged = logged;
}
public bool Logged { get; private set; }
}
}
为什么 MainWindowViewModel 的句柄方法没有从 LoginViewModel 中获取已发布的消息?
感谢您的回复。
答案 0 :(得分:3)
您的MainWindowViewModel
需要实施IHandle<LoginEvent>
。您已经使用正确的签名定义了该方法,因此您只缺少实际告诉编译器您实现接口的部分:
public class MainWindowViewModel
: Conductor<IScreen>.Collection.OneActive, IHandle<LoginEvent>
可以在the documentation找到更多信息。