Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight Custom Control Create Custom Event

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

like image 679
PlayKid Avatar asked Aug 17 '09 10:08

PlayKid


1 Answers

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);
            }
        }
    }
}
like image 131
Jeff Wilcox Avatar answered Sep 19 '22 05:09

Jeff Wilcox