如何创建一个事件来处理自定义控件中另一个控件的单击事件?
这是我所得到的设置:一个文本框和一个按钮(自定义控件),一个silverlight应用程序(使用上面的自定义控件)
我想从主应用程序上的自定义控件公开按钮的click事件,我该怎么做?
谢谢
发布于 2009-08-19 16:02:11
这是一个非常简单的版本,因为我没有使用依赖属性或其他任何东西。它将公开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);
}
}
}
}https://stackoverflow.com/questions/1287294
复制相似问题