5
如何创建一个事件来处理来自我的自定义控件的其他控件之一的单击事件?Silverlight自定义控件创建自定义事件
这里是我有什么设置: 一个文本框和一个按钮(自定义控件) Silverlight应用程序(使用上面的自定义控制)
我想揭露的单击事件按钮从主应用程序的自定义控件上,我该怎么做?
感谢
如何创建一个事件来处理来自我的自定义控件的其他控件之一的单击事件?Silverlight自定义控件创建自定义事件
这里是我有什么设置: 一个文本框和一个按钮(自定义控件) Silverlight应用程序(使用上面的自定义控制)
我想揭露的单击事件按钮从主应用程序的自定义控件上,我该怎么做?
感谢
这里是一个超级简单的版本,因为我没有使用依赖属性或任何东西。它会公开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);
}
}
}
}
您的自定义控件是用户控件(来自UserControl)还是一个真正的控件?您应该能够在文件后面的代码中公开事件,并将其附加到您的子控件的事件以便展示事件。 – 2009-08-17 22:51:11
他们是2个真正的控制合并为1,我只是想暴露按钮的点击事件。 当我在用户控件上工作时,我可以进入点击事件,但是如果我正在处理某些使用用户控件的事件,那么我将无法访问该事件处理程序。 – PlayKid 2009-08-18 05:53:07