简体   繁体   中英

Using a Mediator in WPF MVVM

I have a project implementing a Mediator pattern similar to what is found in this question: Sql, Wpf, Xaml, C#, Binding data, Dynamic resource, accessing to non-static data, Obtaining a Reference to an Object

This seems to work fine when the Register() function is called in the parent view then the SendMessage() function in a child view. The data can easily be obtained that is acquired in the child and then the parent can process it through the Mediator.

However I need to do the opposite. Take data acquired in the parent and pass it to the child to be processed. Can the Mediator be used for this task?

I have tried various methods of placing a call to the Register() function in the child with a SendMessage() in the parent, but since the Register() initializes the collection the records seems to be getting lost.

Am I missing something? Is there a better way?

I had the same problem... i know its not a good Solution but i solved it like this....

In Your ChildView

    public ChildViewModel()
    {
        Messenger.UnRegister(this); //I use reflection and Attributes to register/Unregister you can do it normally
        Messenger.Register(this);
        if (ChildData== null)
        {
            Messenger.NotifyColleagues<object>(
                MessengerMessages.GET_CHILD_DATA,ChildData);
        }            
    }
    [MessengerMessageSink(MessengerMessages.SEND_CHID_DATA,
        ParameterType = typeof (CHILD_DATA))]
    protected void Set_Child_DATA(ChildData childData)
    {
        if (childData!= null)
        {
            //Do Something              
        }
    }

In your ParentView

    public ParentViewModel()
    {
        Messenger.UnRegister(this); //I use reflection and Attributes to register/Unregister you can do it normally
        Messenger.Register(this);            
    }
    [MessengerMessageSink(MessengerMessages.GET_CHILD_DATA,
        ParameterType = typeof (CHILD_DATA))]
    protected void Send_Child_DATA(Object obj)
    {
                        Messenger.NotifyColleagues<object>(
                MessengerMessages.SEND_CHILD_DATA,ChildData);
    }

Here we are calling the parentViewModel to send the required data when the ChildViewModel dosent find the Data it requires....

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