Page 111 附加事件

假设StackPanel包装了一些按钮,并且希望一个事件中处理程序中所有这些按钮的单击事件。粗略的方法是将每个按钮的Click事件关联到同一个事件处理程序。

但是Click支持事件冒泡,从而提供了一个更好的选择。可以通过更高层次元素的Click事件(如StackPanel面板)来处理所有按钮的单击事件。

 1 <Window x:Class="Page111.MainWindow"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 Title="MainWindow" Height="350" Width="525">
5 <Grid>
6 <StackPanel Orientation="Vertical" Margin="30" Click="DoSomething">
7 <Button Margin="10" Width="75" Height="25">Command 1</Button>
8 <Button Margin="10" Width="75" Height="25">Command 2</Button>
9 <Button Margin="10" Width="75" Height="25">Command 3</Button>
10 </StackPanel>
11 </Grid>
12 </Window>

问题是XAML解析器会降上述代码解释成一个错误,因为StackPanel没有Click事件;

解决方法为“对象.事件名”的形式使用不同的关联事件语法。

 1 <Window x:Class="Page111.MainWindow"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 Title="MainWindow" Height="350" Width="525">
5 <Grid>
6 <StackPanel Orientation="Vertical" Margin="30" Button.Click="DoSomething">
7 <Button Margin="10" Width="75" Height="25">Command 1</Button>
8 <Button Margin="10" Width="75" Height="25">Command 2</Button>
9 <Button Margin="10" Width="75" Height="25">Command 3</Button>
10 </StackPanel>
11 </Grid>
12 </Window>

Click事件实际是ButtonBase类中定义的,并且Button类继承了该事件。如果为ButtonBase.Click事件关联事件处理程序,那么当任何继承自ButtonBase(包括Button类、RadioButton类以及CheckBox类)被单击时,都会调用该事件处理程序。如果为Button.Click事件关联事件处理程序,那么事件处理程序就只能被Button对象使用。


 

posted @ 2011-11-08 11:32  jacky_j2ee  阅读(202)  评论(0编辑  收藏  举报