5

How do I create an event that handled a click event of one of my other control from my custom control?

Here is the setup of what I've got: a textbox and a button (Custom Control) a silverlight application (uses that above custom control)

I would like to expose the click event of the button from the custom control on the main application, how do I do that?

Thanks

2
  • Is your custom control a user control (derives from UserControl), or a true Control? You should be able to expose a public event in the code behind file, and attach to your child controls' events in order to surface the event. Commented Aug 17, 2009 at 22:51
  • They are 2 true controls combined into 1, and I just want to exposed the click event of the button. I can get to the click event when I am working on the user control, but if I am working on something consuming the user control, I won't get to that event handler. Commented Aug 18, 2009 at 5:53

1 Answer 1

8

Here's a super simple version, since I'm not using dependency properties or anything. It'll expose the Click property. This assumes the button template part's name is "Button".

using System.Windows;
using System.Windows.Controls;

namespace SilverlightClassLibrary1
{
    [TemplatePart(Name = ButtonName , Type = typeof(Button))]
    public class TemplatedControl1 : Control
    {
        private const string ButtonName = "Button";

        public TemplatedControl1()
        {
            DefaultStyleKey = typeof(TemplatedControl1);
        }

        private Button _button;

        public event RoutedEventHandler Click;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // Detach during re-templating
            if (_button != null)
            {
                _button.Click -= OnButtonTemplatePartClick;
            }

            _button = GetTemplateChild(ButtonName) as Button;

            // Attach to the Click event
            if (_button != null)
            {
                _button.Click += OnButtonTemplatePartClick;
            }
        }

        private void OnButtonTemplatePartClick(object sender, RoutedEventArgs e)
        {
            RoutedEventHandler handler = Click;
            if (handler != null)
            {
                // Consider: do you want to actually bubble up the original
                // Button template part as the "sender", or do you want to send
                // a reference to yourself (probably more appropriate for a
                // control)
                handler(this, e);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.