开发者

MVVMLight toolkit Messenger class causing problems. Firing N times

开发者 https://www.devze.com 2023-03-06 15:06 出处:网络
I have a view named Work.xaml. This Work.xaml contains multiple WorkSkeleton.xaml. The Work.xaml\'s ViewModel is WorkViewModel.

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", c开发者_高级运维ollection =>
    {
        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.

0

精彩评论

暂无评论...
验证码 换一张
取 消