开发者

Passing on events from a UserControl's child control - most direct way?

My UserControl contains a button. I want the button's Click event to be 'passed through' directly to users of the UserControl. They will see it as an event named 'ButtonClick'.

public event RoutedEventHandler ButtonClick  
{  
    add { _button.Click += value; }  
开发者_Python百科    remove { _button.Click -= value; }  
}  

This approach doesn't work. I did add the handler for ButtonClick in the client code, but clicking the button does not invoke it there.

I might be missing something simple because I'm still new to WPF.


You have to register the RoutedEvent:

public static readonly RoutedEvent ButtonClickEvent = EventManager.RegisterRoutedEvent(
    "ButtonClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

.. and then use the property to manage the newly register event handler

public event RoutedEventHandler ButtonClick
    {
        add { AddHandler(ButtonClickEvent , value); } 
        remove { RemoveHandler(ButtonClickEvent , value); }
    }

Then obviously you'll need to raise the Routed Event when the button's click event is triggered:

void button_Click(object sender, EventArgs e)
{
   RaiseEvent(new RoutedEventArgs(ButtonClickEvent));
}

It's a couple steps from just wiring directly to the button's native event handler, but not terrible.


The Button Click event is a routed event, which means that it travels up and down the visual tree of your application, this means that any parent of your button can handle this event. Therefore, you do not have to add your own logic to support this, i.e. your code is redundant!

See the following for how to register a handler for this routed event:

http://msdn.microsoft.com/en-us/library/ms742806.aspx#event_handing

Colin E.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜