C# – wpf custom control events

ccustom-controlsnetwpfwpf-controls

I want to create a custom wpf control that contains a Button and a ContentPresenter. As WPF controls are supposed to be lookless I created a class that is supposed to contain my control's behaviour and I put default style for the control inside generic.xaml file. So far so good.

But how do I make my button raise an event (routed event?) and handle it in my control's class? I figured out that I can add code behind file for the ResourceDictionary from generic.xaml and put my event handlers there, but that would associate behaviour of my control with its template and is therefore not desirable. Another idea I have seen (but not yet tried) is to use TemplatePart mechanism to locate some key controls inside the template and subscribe to events in code. But that does not seem flexible enough for me because it may happen that the user of my control will want to replace button with a control that does not have any event I know of at the time of designing my control.

So how do I raise event in XAML when button is clicked and subscribe to it in my control's code file?

Best Answer

Override the OnApplyTemplate method of the control.

That is where you know the template has been applied and you can use GetTemplateChild to get a reference to a control.

E.g.:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    var myButton = this.GetTemplateChild("myButton") as Button;
    if(myButton != null)
    {
        myButton.Click += ...;
}
Related Topic