WPF中的Event
Routed Events 意指一个事件在一个相互关联的元素组成的树中传递,而非直接传递到一个特定的目标。
它可以在两个方向进行传递,Bubbling, tunneling
事件Routed的三种方式
1〉 Bubbling:事件由源头传递到元素树的最顶点
2〉 tunneling:事件由树的顶端传递的源头
3〉 direct:事件不在树中移动,表现方式类同标准的CLR事件
如何写Routed Event
示例:
Public static readonly RoutedEvent TapEvent =
EventManager.RegisterRoutedEvent(“Tap”,
RoutingStrategy.Bubble,
typeof(RoutedEventHandle),
typeof(MyButtonSimple)
);
// Provide CLR accessors for the event
Public event RoutedEventHandle Tap
{
Add{AddHandler(TapEvent, value);}
Remove{RemoveHandler(TapEvent, value);}
}
如何在Xaml关联事件
<Button Click=”blSetColor”>button</Button>
为什么要使用Routed Event
对于一组需要交互的控件,可以将父元素作为一个通用的事件监听者,然后使用同一个事件函数来处理交互。
示例如下
A grouped button set
XAML
<Border Height="50" Width="300" BorderBrush="Gray" BorderThickness="1">
<StackPanel Background="LightGray" Orientation="Horizontal" Button.Click="CommonClickHandler">
<Button Name="YesButton" Width="Auto" >Yes</Button>
<Button Name="NoButton" Width="Auto" >No</Button>
<Button Name="CancelButton" Width="Auto" >Cancel</Button>
</StackPanel>
</Border>
C#
Private void CommonClickHandler(object sender, RoutedEventArgs e)
{
FrameworkElement feSource = e.Source as FrameworkElement;
Switch(feSource.Name)
{
Case “YesButton”:
// do something here
Break;
Case “NoButton”
// do something
Break;
Case “CancelButton”:
// do something
Break;
}
e.Handled = true;
}
自定义Event
示例如下:
//Invoke该事件
protected virtual void OnPipeValueChanged(double oldValue, double newValue)
{
RoutedPropertyChangedEventArgs<double> args = new RoutedPropertyChangedEventArgs<double>(oldValue, newValue);
args.RoutedEvent = PipeControl.PipeValueChangedEvent;
RaiseEvent(args);
}
// 注册该事件
public static readonly RoutedEvent PipeValueChangedEvent =
EventManager.RegisterRoutedEvent("PipeValueChanged",
RoutingStrategy.Bubble,
typeof(RoutedPropertyChangedEventHandler<double>),
typeof(PipeControl));