5

I'm trying to decide the best way to handle communication between a UserControl that is nested within another UserControl and the parent Form itself. I have a Form, inside the form there's a UserControl with a TabControl. Each tab in that is also represented with a UserControl.

An object (for binding) gets instantiated at the form and then passed to a property in the first UC, which then passes it on to a property on the nested UC. Each UC uses a BindingSource to wire up the actual input controls. This daisy chaining behavior gets to be cumbersome. Now I want to send a Save command back to the main form, so I need to daisy-chain some events back up to the form.

I feel the entire object shouldn't be owned by the parent form at all. The object pretty much drives this entire application, but because the Form and UI was growing to be a maintenance nightmare, I started breaking up UI components into UserControls.

I guess my questions are: - Would this be a good place for some sort of Service Locator pattern? - Should I just keep it simple with a static singleton instance of this object that can be accessed from any control? - Are there any other patterns that could be helpful that you could recommend?

4

You can use the Mediator pattern.

essentially you have a single object to which you bind events and pass that into view models rather than binding to the viewmodel event. so:

public interface IMediator
{
    void NotifyColleagues(string token, object args);
    void Register(string token, Action<object> callback);
    void Unregister(string token, Action<object> callback);
}

..in main VM

Mediator.Register("start_Click", OnStart);

..in sub VM

Mediator.NotifyColleagues("start_Click", this.data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.