在WPF自定义附加事件 [英] Custom attached events in WPF
问题描述
我可能是错在这里得到的术语,但我认为我试图创建一个附加事件。
I might be getting the terminology wrong here, but I think I'm trying to create an attached event.
在表面SDK,你可以做这样的事情
In the Surface SDK, you can do things like:
<Grid Background="{StaticResource WindowBackground}" x:Name="Foo" s:SurfaceFrameworkElement.ContactChanged="Foo_ContactChanged"/>
我要创建哪些处理程序可以在XAML中以同样的方式被添加自定义事件,但我有麻烦了。
I want to create a custom event for which a handler can be added in XAML in the same way, but I'm having trouble.
我可以创建自定义路由事件,但XAML IntelliSense不看到它和事件处理程序不加,如果我只是定期输入。这里是我的事件定义:
I can create a custom routed event, but the XAML intellisense doesn't see it and the event handler isn't added if I just type it in regularly. Here is my event definition:
public static class TagRectEvents
{
public static readonly RoutedEvent TagRectEnterEvent = EventManager.RegisterRoutedEvent(
"TagRectEnter", RoutingStrategy.Bubble, typeof( RoutedEventHandler ), typeof( TagRectEvents ) );
public static void AddTagRectEnterHandler( DependencyObject d, RoutedEventHandler handler )
{
UIElement element = d as UIElement;
if ( element == null )
{
return;
}
element.AddHandler( TagRectEvents.TagRectEnterEvent, handler );
}
public static void RemoveTagRectEnterHandler( DependencyObject d, RoutedEventHandler handler )
{
UIElement element = d as UIElement;
if ( element == null )
{
return;
}
element.RemoveHandler( TagRectEvents.TagRectEnterEvent, handler );
}
}
我是不是要去了解这一切错了吗?所有的附加行为的例子我看到的是更多的元素添加附加属性,然后做的事情,设置该属性。
Am I just going about it all wrong? All of the "attached behavior" examples I see are more about adding an attached property, and then doing things with elements that set that property.
推荐答案
您必须或者不能映射命名空间,和/或附加事件如地方:TagRectEvents.TagRectEnterEvent
。你必须使用 TagRectEnter
,而不是 TagRectEnterEvent
。
You must either be not mapping the namespace, and/or attaching event like local:TagRectEvents.TagRectEnterEvent
. You have to use TagRectEnter
, and not TagRectEnterEvent
.
命名空间映射:
xmlns:local="clr-namespace:WpfInfrastructure.WpfAttachedEvents"
用法:
<Button Content="Press" local:TagRectEvents.TagRectEnter="MyHandler" Margin="25,43,36,161" />
处理器:
Handler :
public void MyHandler(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Hurray!");
}
我用你的代码,它工作正常这里。
I used your code, it works correctly here.
这篇关于在WPF自定义附加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!