您的位置:首页 > 其它

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

2008-03-09 13:34 246 查看
附加事件

当树上元素公开了路由事件时,按上升或下降方式传递它是很自然的,但是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的上升式事件SelectionChanged和Button的Click。这两个路由事件定义在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]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: