[简译]WPF的新特性——路由事件(3)

附加事件

 

       当树上元素公开了路由事件时,按上升或下降方式传递它是很自然的,但是WPF还支持在没有定义路由事件的元素上上下传递另外的路由事件!这要感谢“附加事件”(attached events)表示法。

 

       附加事件的操作非常像附加属性(其上/下传递的方式与附加属性的继承非常类似)。下例再次改变了AboutDialog

 

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        x:Class="AboutDialog"

        ListBox.SelectionChanged="ListBox_SelectionChanged"

        Button.Click="Button_Click"

        Title="关于WPF揭秘" SizeToContent="WidthAndHeight" Background="OrangeRed">

    <StackPanel>

       <Label FontWeight="Bold" FontSize="20" Foreground="White">

           WPF揭秘(版本3.0

       </Label>

       <Label>(C)2006 SAMS 出版集团</Label>

       <Label>已安装的章节:</Label>

       <ListBox>

           <ListBoxItem>第一章</ListBoxItem>

           <ListBoxItem>第二章</ListBoxItem>

       </ListBox>

       <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

           <Button MinWidth="75" Margin="10">Help</Button>

           <Button MinWidth="75" Margin="10">OK</Button>

       </StackPanel>

       <StatusBar>您已经成功注册了本产品。</StatusBar>

    </StackPanel>

</Window>

 

public partial class AboutDialog : Window

    {

       public AboutDialog()

       {

           InitializeComponent();

       }

 

       private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)

       {

           if (e.AddedItems.Count > 0)

              MessageBox.Show("您选择了 " + e.AddedItems[0]);

       }

 

       private void Button_Click(object sender, RoutedEventArgs e)

       {

           MessageBox.Show("您单击了 " + e.Source);

       }

    }

 

       上例中,AboutDialog处理了两个不属于它(Window)的事件——ListBox的上升式事件SelectionChangedButtonClick。这两个路由事件定义在Window元素中,因此需要添加所属类的名称作为前缀。

 

       每个路由事件都可以被用作附加事件。在编译时,XAML编译器看到的Click事件是定义在Button中的;在运行时,系统直接调用AddHandler方法来将这两个事件附加到Window对象上。因此,它们等价于下面的C#代码:

 

public AboutDialog()

    {

        InitializeComponent();

        this.AddHandler(ListBox.SelectionChangedEvent,

           new SelectionChangedEventHandler(ListBox_SelectionChanged));

        this.AddHandler(Button.ClickEvent,

           new RoutedEventHandler(Button_Click));

    }

 

       由于路由事件携带丰富的信息,因此我们可以在一个通用的事件处理器中处理它们,如下所示:

 

private void GenericHandler(object sender, RoutedEventArgs e)

    {

        if (e.RoutedEvent == Button.ClickEvent)

        {

           MessageBox.Show("您单击了 " + e.Source);

        }

        else if (e.RoutedEvent == ListBox.SelectionChangedEvent)

        {

           SelectionChangedEventArgs sce = (SelectionChangedEventArgs)e;

           if (sce.AddedItems.Count > 0)

               MessageBox.Show("您选择了 " + sce.AddedItems[0]);

        }

    }

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值