views:

2047

answers:

2

Hi There,

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

A: 

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);
            }
        }
    }
}
Jeff Wilcox
A: 

I have a similar problem with a C# custom control...in fact identical; the control is a panel with a button and I would like to expose the click event to the class using an instance of the control but I can't seem to follow the above code. Can anyone point me in the right direction or take a stab at clarifying?

Thanks,

Chris

Chris