WPF自定义RoutedEvent事件示例代码

*************************
引用网友,便于查找所用.....
创建自定义路由事件和应用分为6个步骤:

(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);

}

5.1 Xaml访问自定义控件与引用自定义事件
<local:MyObject Width="80" Height="25" Background="Blue" MyObjectAutoSNHandler="MyObject_MyObjectAutoSNHandler" />
5.2 通过代码方式,添加监听路由事件
this.ContainerName.AddHandler(MyObject.MyObjectRoutedEvent, new RoutedEventHandler(MyObject_MyObjectAutoSNHandler));
6.事件处理behindcode
void MyObject_MyObjectAutoSNHandler(object sender, MyObjectRoutedEventArgs e)
{
      string sn=e.SerialNumber;
}
 
 
*************************
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);
posted @ 2016-07-27 09:24  jeffery1010  Views(2551)  Comments(0Edit  收藏  举报