简体   繁体   中英

MVVMLight toolkit Messenger class causing problems. Firing N times

I have a view named Work.xaml. This Work.xaml contains multiple WorkSkeleton.xaml. The Work.xaml's ViewModel is WorkViewModel.

The Work.xaml is contained in MainPage.xaml which has button to load 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:

    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 :-

 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. This happens N times. If I clicked the button Nth time the message will be received N times in Work.xaml.cs. 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. On click of Work button the instance is completely new. Then why is it firing N times?

Are you sure it's firing N times for the same instance? You probably have N instances lying around (N-1 waiting to be garbage collected) and that's why you're seeing it N times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM