我如何创建一个事件来处理来 self 的自定义控件的另一个控件的点击事件?
这是我的设置: 一个文本框和一个按钮(自定义控件) 一个 silverlight 应用程序(使用上面的自定义控件)
我想从主应用程序的自定义控件中公开按钮的点击事件,我该怎么做?
谢谢
最佳答案
这是一个 super 简单的版本,因为我没有使用依赖属性或任何东西。它将公开 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);
}
}
}
}
关于c# - Silverlight 自定义控件创建自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1287294/