心海巨澜

天行键,君子以自强不息;地势坤,君子以厚德载物!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

     本部分介绍SilverLight元素的相关事件。UIElement是所有元素的基础,所有对象都是从这个元素派生而来。UIElement有十个事件:GotFocusLostFocusKeyDownKeyUpMouseEnterMouseLeaveMouseMoveMouseLeftButtonDownMouseLeftButtonUp、Loaded。对于单个控件还会有自已特有的事件,比如Click、Checked、SelectionChanged等。另外,在这些事件中还包括一种路由事件。

     路由事件由 RoutedEventHandler 委托定义,并且由事件处理程序接收 RoutedEventArgs 对象,该对象包含用于确认引发此事件的对象的 Source 属性(如果此事件最初由可视树中的深层对象引发,则该属性不同于传递给事件处理程序的发送者参数)。在 WPF 中,事件路由可以在可视树中事件上下传递;但在Siverlight 中,事件只能向上传递,即“冒泡”操作,也就是父控件可以接收和处理子控件的事件。 下面以键盘事件和鼠标事件为例来介绍路由事件。

1、键盘事件:支持路由事件,KeyDown事件代码如下:

    <Grid x:Name="LayoutRoot" Background="White" KeyDown="LayoutRoot_KeyDown">

        <StackPanel HorizontalAlignment="Center" Margin="0,20,0,0">

            <TextBox x:Name="txtOne" Text="This is txtOne" IsReadOnly="True" Width="200" Height="30" Background="Coral" Foreground="White" FontSize="20" Margin="5"></TextBox>

            <TextBox x:Name="txtTwo" Text="This is txtTwo" IsReadOnly="True" Width="200" Height="30" Background="Coral" Foreground="White" FontSize="20" Margin="5"></TextBox>

            <TextBlock x:Name="txtBlock" FontSize="20" Foreground="Coral" Margin="5"/>

        </StackPanel>

    </Grid>

        private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
            {
                txtBlock.Text = "Control+C";
            }
            else
            {
                txtBlock.Text = e.Key.ToString();
            }
            txtBlock.Text += ":Event From ";
            txtBlock.Text += (e.Source as FrameworkElement).Name;
        }

运行效果如下(按下键,测试一下):

2、鼠标事件:MouseEnterMouseLeave不支持路由事件;MouseMoveMouseLeftButtonDownMouseLeftButtonUp支持路由事件。MouseLeftButtonDown事件代码如下:

    <Grid x:Name="LayoutRoot" Background="White" MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown">

        <StackPanel HorizontalAlignment="Center" Margin="0,20,0,0">

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

                <Rectangle x:Name="rectRed" Width="100" Height="50" Fill="Red" RadiusX="20" RadiusY="20" Margin="5"></Rectangle>

                <Rectangle x:Name="rectGreen" Width="100" Height="50" Fill="Green" RadiusX="20" RadiusY="20" Margin="5"></Rectangle>

            </StackPanel>

            <TextBlock x:Name="txtBlock" FontSize="20" Foreground="Coral" Margin="5" HorizontalAlignment="Center"/>

        </StackPanel>

    </Grid>

        private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            txtBlock.Text = "MouseLeftButtonDown:Event From ";
            txtBlock.Text += (e.Source as FrameworkElement).Name;
        }

运行效果如下(按下鼠标左键,测试一下):

     

     综述:本部分介绍了事件处理,主要介绍了路由事件,我们将在下一讲介绍SilverLight的样式、模板与VSM

posted on 2008-10-10 09:50  心海巨澜  阅读(355)  评论(0编辑  收藏  举报