开发者

How a Winform custom control can notify another Winform Custom Control?

Let's say in a custom control I def开发者_开发问答ined some custom event myEvent. Now when raising event, this event will be captured by the parent form.

How can I capture this event in another custom control which would be on the same parent form ? I'd like the other control to subscribe to the first control event somehow.


I've run into a similar situation a lot when dealing with MVC. The way that I like to handle it is to use a mediator design pattern in the controller.

Basically, you have a class that has a register function and a notify function. The register function takes an object that implements a listener interface and a messageId. It stores these in a dictionary. The notify function takes a messageId for the event that needs to be sent to the listeners and notifies the appropriate ones that the event has occurred.

So maybe something along the lines of

public interface IListener
{
void MessageRaised(int messageId, params object[] arguments);
}

public class Mediator
{
public void Register(IListener listener, int messageId)
{
//... add to dictionary of arrays for each messageId
}

public void NotifyListeners(int messageId, params object[] arguments)
{
//... loop through listeners for the messageId and call the MessageRaised function for each one
}
}

Now normally I have a base controller and it implements a static Mediator object. Then all my other controllers inherit from it. If you are using the code behind and cannot inherit, then you might try using a singleton pattern. .Net static classes are pretty great too since they have a constructor so you could use that as well.

So in your case, I would have the code behind for each control implement IListener and then in the constructor for each one, have something like Mediator.GetInstance().Register(this, Messages.MyEvent). That is kind of a quick and dirty way which can be refactored a bit in the future to make it a bit more reusable.

Some resources from a quick google search

http://www.avajava.com/tutorials/lessons/mediator-pattern.html

http://sourcemaking.com/design_patterns/mediator

Good luck


You could use Event Handling and delegates for that and have your Receiver Control subscribe indirectly to your Sender Control's event, VIA the parent control of both controls, acting as a multiplexer.


The answer is simple. Declare a method in the second form (the one without the event) with the correct signature and mark it as public.

In the parent form assign the method of the second form to the event of the first.


Yes just publish and raise an event and subscribe to it from your listener control.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜