【发布时间】:2015-03-16 14:47:05
【问题描述】:
我正在学习以下教程http://www.mindscapehq.com/blog/index.php/2012/2/1/caliburn-micro-part-4-the-event-aggregator/ 我目前停留在发布/订阅部分。
我已设置好所有内容,因此它应该实际发布事件,但订阅视图模型没有收到消息。
我做了以下事情:
发布 ViewModel:
[Export(typeof(ColorViewModel))]
public class ColorViewModel : PropertyChangedBase
{
private readonly IEventAggregator events;
[ImportingConstructor]
public ColorViewModel(IEventAggregator events)
{
this.events = events;
}
public void Red()
{
this.events.PublishOnUIThread(new ColorEvent(new SolidColorBrush(Colors.Red)));
}
public void Green()
{
this.events.PublishOnUIThread(new ColorEvent(new SolidColorBrush(Colors.Green)));
}
public void Blue()
{
this.events.PublishOnUIThread(new ColorEvent(new SolidColorBrush(Colors.Blue)));
}
}
订阅 ViewModel:
[Export(typeof(AppViewModel))]
public class AppViewModel : PropertyChangedBase, IAppViewModel, IHandle<ColorEvent>
{
private IEventAggregator events;
[ImportingConstructor]
public AppViewModel(ColorViewModel colorViewModel, IEventAggregator events)
{
this.ColorViewModel = colorViewModel;
this.events = events;
this.events.Subscribe(this);
}
public ColorViewModel ColorViewModel { get; private set; }
private SolidColorBrush color;
public SolidColorBrush Color
{
get
{
return this.color;
}
set
{
this.color = value;
this.NotifyOfPropertyChange(() => this.Color);
}
}
public void Handle(ColorEvent message)
{
this.Color = message.Color;
}
}
ColorView 上有 3 个单选按钮,我可以单击它们并进入 Red()、Green()、Blue() 方法,以便调用 PublishOnUIThread。 但我从来没有达到 AppViewModel 的 Handle(ColorEvent) 方法。
我是否遗漏了什么,或者为什么在发布 ColorEvents 后我的 handle 方法没有被调用?
提前致谢
【问题讨论】:
-
事件聚合器从何而来?
AppViewModel和ColorViewModel之间是否共享同一个实例? -
嗨,杰克,感谢您的评论。事件聚合器由 Ninject 注入,所以是的,它在两个视图模型中应该是相同的
-
事件聚合器是否注册为单例或 Ninject 中的任何等价物?
-
您能否将您的容器设置代码添加到问题中?
-
噢噢噢!不,不是......我已经改变了它,使它在单例范围内运行,现在它可以工作了:)谢谢!您可以将此添加为答案,以便我接受它:)
标签: c# wpf caliburn.micro publish-subscribe