1

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?

1 Answer 1

2

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 += ...;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This method assumes that I know that the control template has a "Button" named "myButton" and that I want to subscribe to "Click" event. I do not want to make such assumptions. The user should be able to change it to "Label" named "myLabel" that raises "MouseEnter" event.
in that case make sure that the template triggers a Command and handle the implement the Execute method. Using blend behaviors you can have any event execute the command.
I tried reading about commands, but I still don't know how to use them in this case. Do I need to create my own object implementing ICommand interface or can I reuse generic commands? How do I reference it in XAML? I have seen some examples that claim the command has to be a public static property in static class - then how do I pass instance of the object on which the operation should be performed to the command? Do I need to use CommandTarget?
I finally managed to find an article that describes how to solve my problem: keyvan.io/how-to-add-commands-to-custom-wpf-control While your answer is not exactly what I expected, it helped me to some degree so adding +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.