[英]MVVMLight toolkit Messenger class causing problems. Firing N times
I have a view named Work.xaml.我有一个名为 Work.xaml 的视图。 This Work.xaml contains multiple WorkSkeleton.xaml.
此 Work.xaml 包含多个 WorkSkeleton.xaml。 The Work.xaml's ViewModel is WorkViewModel.
Work.xaml 的 ViewModel 是 WorkViewModel。
The Work.xaml is contained in MainPage.xaml which has button to load Work.xaml. Work.xaml 包含在 MainPage.xaml 中,它具有用于加载 Work.xaml 的按钮。 I hope I am clear till now.
我希望我清楚到现在。 The button's event handler is simple :-
按钮的事件处理程序很简单:-
private void hypMyWork_Click(object sender, RoutedEventArgs e)
{
ShowGridContent(new Work());
}
private void ShowGridContent(UserControl control)
{
gridContent.Children.Clear();
gridContent.Children.Add(control);
}
In my Work.xaml.cs's Constructor I have registered for Messages of type ObservableCollection:在我的 Work.xaml.cs 的构造函数中,我注册了 ObservableCollection 类型的消息:
Messenger.Default.Register<ObservableCollection<WorkEducation>>(this, "BindWorkEducationList", collection =>
{
foreach (var item in collection)
{
if (item.IsEducationInfo == false)
{
WorkEducationSkeleton skeleton = new WorkEducationSkeleton();
skeleton.WorkEducation = item;
stkPanel.Children.Insert(0,skeleton);
}
}
});
The ViewModel is sending this message when the ObservableCollection is loaded like this :-当 ObservableCollection 像这样加载时,ViewModel 正在发送此消息:-
Messenger.Default.Send<ObservableCollection<WorkEducation>>(WorkEducation,
"BindWorkEducationList");
Everything works fine the 1st time.第一次一切正常。 But as soon as I click the Work button in MainPage.xaml to load the Work page 2nd time, the messages are received in my Work.xaml 2 times which adds the same items to stackpanel again and again.
但是,只要我第二次单击 MainPage.xaml 中的“工作”按钮加载工作页面,消息就会在我的 Work.xaml 中收到 2 次,这一次又一次地将相同的项目添加到堆栈面板。 This happens N times.
这种情况发生 N 次。 If I clicked the button Nth time the message will be received N times in Work.xaml.cs.
如果我第 N 次单击按钮,消息将在 Work.xaml.cs 中收到 N 次。 But how is this possible?
但这怎么可能呢?
I have clearly specified the recepient in Work.xaml.cs to be this
as the 1st parameter which means the message is to be received for this particular instance.我已经明确规定在Work.xaml.cs的recepient是
this
为这意味着该消息是用于此特定实例要接收的第一参数。 On click of Work button the instance is completely new.单击“工作”按钮,实例是全新的。 Then why is it firing N times?
那为什么要开N次呢?
Are you sure it's firing N times for the same instance?你确定它会为同一个实例触发 N 次吗? You probably have N instances lying around (N-1 waiting to be garbage collected) and that's why you're seeing it N times.
您可能有 N 个实例(N-1 个等待被垃圾收集),这就是您看到它 N 次的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.