自定义路由事件

WpfApplication1.DXSL.BLL。 ReportTimeEventArgs TimeButton
namespace WpfApplication1.DXSL.BLL
{
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows;
 
    #region ReportTimeEventArgs
    public class ReportTimeEventArgs : RoutedEventArgs
    {
        public ReportTimeEventArgs(RoutedEvent routedEvent, object source) :
            base(routedEvent, source)
        {

        }

        public DateTime ClickTime { get; set; }
    }

    public class TimeButton : Button
    {
        public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent
            ("ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeEventArgs>), typeof(TimeButton));

        public event RoutedEventHandler ReportTime
        {
            add
            {
                this.AddHandler(ReportTimeEvent, value);
            }
            remove
            {
                this.RemoveHandler(ReportTimeEvent, value);
            }
        }

        protected override void OnClick()
        {
            base.OnClick();

            ReportTimeEventArgs args = new ReportTimeEventArgs(ReportTimeEvent, this);
            args.ClickTime = DateTime.Now;
            this.RaiseEvent(args);
        }
    }
    #endregion
  
}
WpfApplication1.WpfApplicationButton
<Window x:Class="WpfApplication1.WpfApplicationButton"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1.DXSL.BLL" Title="Routed Event"
        Height="300" Width="300"
          local:TimeButton.ReportTime="ReprotTimeHandler">
    <Grid x:Name="grid_1" local:TimeButton.ReportTime="ReprotTimeHandler">
        <Grid x:Name="grid_2" local:TimeButton.ReportTime="ReprotTimeHandler">
            <Grid x:Name="grid_3" local:TimeButton.ReportTime="ReprotTimeHandler">
                <StackPanel x:Name="stackPanel_1">
                    <ListBox x:Name="listBox"></ListBox>
                    <local:TimeButton x:Name="timeButton" Width="80" Height="80"
                                      Content="报时" local:TimeButton.ReportTime="ReprotTimeHandler" />
                </StackPanel>
            </Grid>
        </Grid>
    </Grid>
</Window>

  运行前                    RoutingStrategy.Bubble            RoutingStrategy.Tunnel

 

例子来自《wpf深入浅出》一书。

posted @ 2013-03-28 11:13  石 磊  阅读(356)  评论(0编辑  收藏  举报