我喜欢带有自定义触发器的想法,但我没有设法使其工作(某些方法已更改或不推荐使用,因此上面显示的定义SpaceKeyDownEventTrigger
现在未编译)。所以,我把自定义的工作版本放在这里RoutedEvent
。SpaceKeyDownEvent
是在MyControl
自定义控件中定义的,并且在到达未处理的附加事件并且按下的键是空格键时从方法OnKeyDown
中KeyDown
引发MyControl
。
public class MyControl : ContentControl
{
// This constructor is provided automatically if you
// add a Custom Control (WPF) to your project
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(MyControl),
new FrameworkPropertyMetadata(typeof(MyControl)));
}
// Create a custom routed event by first registering a RoutedEventID
// This event uses the bubbling routing strategy
public static readonly RoutedEvent SpaceKeyDownEvent = EventManager.RegisterRoutedEvent(
"SpaceKeyDown",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MyControl));
// Provide CLR accessors for the event
public event RoutedEventHandler SpaceKeyDown
{
add { AddHandler(SpaceKeyDownEvent, value); }
remove { RemoveHandler(SpaceKeyDownEvent, value); }
}
// This method raises the SpaceKeyDown event
protected virtual void RaiseSpaceKeyDownEvent()
{
RoutedEventArgs args = new RoutedEventArgs(SpaceKeyDownEvent);
RaiseEvent(args);
}
// Here KeyDown attached event is customized for the desired key
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Space)
RaiseSpaceKeyDownEvent();
}
}
MyControl
可以添加到另一个控件的模板中,允许后者与EventTrigger
路由SpaceKeyDown
事件一起使用:
<Style TargetType="{x:Type local:MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyControl}">
<Grid>
<ContentPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Adding MyControl to the TextBox template -->
<Style TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<local:MyControl>
<ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</local:MyControl>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<EventTrigger RoutedEvent="local:MyControl.SpaceKeyDown">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Foreground.Color"
From="White" To="Transparent" Duration="0:0:0.066" AutoReverse="True" RepeatBehavior="3x"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>