简体   繁体   English

Silverlight自定义控件创建自定义事件

[英]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) 以下是我所拥有的设置:文本框和按钮(自定义控件)Silverlight应用程序(使用上面的自定义控件)

I would like to expose the click event of the button from the custom control on the main application, how do I do that? 我想从主应用程序的自定义控件中公开按钮的click事件,我该怎么做?

Thanks 谢谢

Here's a super simple version, since I'm not using dependency properties or anything. 这是一个超级简单的版本,因为我没有使用依赖属性或任何东西。 It'll expose the Click property. 它将公开Click属性。 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);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM