我该如何创建一个事件,来处理我的自定义控件中的某个其他控件的点击事件?
这是我的设置: 一个文本框和一个按钮(自定义控件) 一个使用上述自定义控件的Silverlight应用程序
我想在主应用程序中公开自定义控件中按钮的点击事件,我该怎么做?
谢谢
我该如何创建一个事件,来处理我的自定义控件中的某个其他控件的点击事件?
这是我的设置: 一个文本框和一个按钮(自定义控件) 一个使用上述自定义控件的Silverlight应用程序
我想在主应用程序中公开自定义控件中按钮的点击事件,我该怎么做?
谢谢
这是一个非常简单的版本,因为我没有使用依赖属性或其他东西。它将公开Click属性。这假定按钮模板部件的名称为“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);
}
}
}
}