我想使用DependencyProperties将自定义事件处理程序添加到默认框架元素. 类似于以下内容: Border custom:MyProps.HandleMyEvent="someHandler".../Border 以下是包含Border元素的控件的代码: public class My
类似于以下内容:
<Border custom:MyProps.HandleMyEvent="someHandler">...</Border>
以下是包含Border元素的控件的代码:
public class MyPage : Page{
public void someHandler(object sender, EventArgs e){
//do something
}
}
以下是我如何想象定义属性的类的粗略示例:
public class MyProps{
public event EventHandler MyInternalHandler;
public static readonly DependencyProperty HandleMyEventProperty = ...
public void SetHandleMyEvent(object sender, EventHandler e){
MyInternalHandler += e;
}
}
问题是我不知道/没有找到任何提示如何将DependencyProperties与事件/委托和EventHandlers结合起来.
你有线索吗?
我将假设这与WPF无关,这是一个银色问题.首先,您不能简单地将事件添加到现有控件.毕竟你要添加附加的属性,而事件的处理方式不同,它们不是属性.
您需要创建一个具有此事件的新类型,然后创建此类型的附加属性.
这是一个只有一个事件的基本类型: –
public class MyEventer
{
public event EventHandler MyEvent;
// What would call this??
protected void OnMyEvent(EventArgs e)
{
if (MyEvent != null)
MyEvent(this, e);
}
}
现在我们创建一个以MyEventer为属性的附加属性,我更喜欢将它们放在一个单独的静态类中.
public static class MyProps
{
public static MyEventer GetEventer(DependencyObject obj)
{
return (MyEventer)obj.GetValue(EventerProperty );
}
public static void SetEventer(DependencyObject obj, MyEventer value)
{
obj.SetValue(EventerProperty , value);
}
public static readonly DependencyProperty EventerProperty =
DepencencyProperty.RegisterAttached("Eventer", typeof(MyEventer), typeof(MyProps), null)
}
}
现在你将它附加到这样的控件: –
<Border ...>
<custom:MyProps.Eventer>
<custom:MyEventer MyEvent="someHandler" />
</custom:MyProps.Eventer>
</Border>
如果在编写此xaml之前编译项目,您将注意到Visual Studio将为您提供选项,以便在您的代码中创建事件处理程序.
当然,这仍然留下了一个重要的问题:你是如何打算引发事件的?
