您的位置:首页 > 其它

Page 111 附加事件

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

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

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


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

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

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


Click事件实际是ButtonBase类中定义的,并且Button类继承了该事件。如果为ButtonBase.Click事件关联事件处理程序,那么当任何继承自ButtonBase(包括Button类、RadioButton类以及CheckBox类)被单击时,都会调用该事件处理程序。如果为Button.Click事件关联事件处理程序,那么事件处理程序就只能被Button对象使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: