WPF自定义RoutedEvent事件示例代码
(1)自定义路由事件参数对象
(2)声明并注册路由事件
(3)为路由事件添加CLR事件包装
(4)创建可以激发路由事件的方法
(5)Xaml(behind code引用)
(6)事件处理
public class MyObjectRoutedEventArgs:RoutedEventArgs{
public MyObjectRoutedEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
public DateTime ClickTime { get; set; }
}
public class MyObject:Button{
//注册实例化路由事件,Bubble\Direct\Tunnel
public static readonly RoutedEvent MyObjectRoutedEvent
=EventManager.RegisterRoutedEvent("OnMyObjectClick",RoutingStrategy.Bubble
,typeof(EventHandler<MyObjectRoutedEventArgs>),typeof(MyObject);
//CLR包装
public Event RoutedEventHandler MyObjectAutoSNHandler{
add{this.AddHanler{MyObjectRoutedEvent,value};}
remove{this.RemoveHanler{MyObjectRoutedEvent,value};}}
}
public override OnClick(){
base.OnClick();
MyObjectRoutedEventArgs args=new MyObjectRoutedEventArgs();
args.SerialNumber="生成流水号";
args.Subject="生成主题";
使用RaiseEvent(args)来触发路由事件
this.RaiseEvent(args);
}
public
static
readonly
DependencyProperty PageIndexProperty =
DependencyProperty.Register(
"PageIndex"
,
typeof
(
int
),
typeof
(MoonPdfPanel),
new
UIPropertyMetadata(1));
public
int
PageIndex
{
get
{
return
(
int
)GetValue(PageIndexProperty);}
set
{ SetValue(PageIndexProperty, value); }
}
public
static
readonly
RoutedEvent PageIndexChangedEvent = EventManager.RegisterRoutedEvent(
"PageIndexChanged"
, RoutingStrategy.Bubble,
typeof
(RoutedPropertyChangedEventHandler<
int
>),
typeof
(MoonPdfPanel));
public
event
RoutedPropertyChangedEventHandler<
int
> PageIndexChanged
{
add { AddHandler(PageIndexChangedEvent, value); }
remove { RemoveHandler(PageIndexChangedEvent, value); }
}
// 触发事件,结尾一定要使用RaiseEvent(args)来触发路由事件。
RoutedPropertyChangedEventArgs<
int
> args =
new
RoutedPropertyChangedEventArgs<
int
>(
val,
this
.GetCurrentPageNumber(), PageIndexChangedEvent);
this
.RaiseEvent(args);