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

时间:2009-08-17 10:47:05

标签: c# silverlight events custom-controls

如何创建一个事件来处理来自我的自定义控件的其他控件之一的click事件?

以下是我所拥有的设置: 文本框和按钮(自定义控件) Silverlight应用程序(使用上面的自定义控件)

我想从主应用程序的自定义控件中公开按钮的click事件,我该怎么做?

由于

1 个答案:

答案 0 :(得分:8)

这是一个超级简单的版本,因为我没有使用依赖属性或任何东西。它将公开Click属性。这假设按钮模板部件的名称是“按钮”。

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);
            }
        }
    }
}