1. 程式人生 > >WPF 路由事件簡單例項

WPF 路由事件簡單例項

在Winform窗體中,新增一個按鈕然後雙擊按鈕就可以在.cs程式碼自動生成有關事件的程式碼,這就是一個簡單的事件模型,但是如果對於大型的設計介面,數量過多的控制元件通過每次都生成相關的時間程式碼,將是一個好大的時間與控制元件的浪費,如何解決這個問題,可以用路由事件解決(通俗籠統的解釋,詳解自行查閱),路由事件包括(隧道路由,冒泡路由)

1.下面我們從例項開始;

//將路由事件放入 MainWindow()建構函式中訂閱 

 

 public void InitialTxtChange()
        {
            this.Power_Value.AddHandler(TextBox.KeyDownEvent, new RoutedEventHandler(Txt_Tension));
            this.Grid_RadioButton.AddHandler(RadioButton.ClickEvent, new RoutedEventHandler(Rtn_Tension));

        }

   /// <summary>
        /// 點選選擇正面或反面
        /// </summary>
        private void Rtn_Tension(object sender, RoutedEventArgs e)
        {
                UIElement s = (UIElement)e.OriginalSource;   //可視樹起始元素            
                RadioButton Rad = new RadioButton();
                Rad = s as RadioButton;      //獲取選中的控制元件

               //RadioButton Rad =new RadioButton();

                 //Rad= RadioButton as Sender
                switch (Rad.Name)   //根據選中的控制元件名稱進行操作
                {
                    case "Rtn_Front": MessageBox.Show("正面"); break;
                    case "Rtn_Back" :  MessageBox.Show("背面"; break;
                }
        } 

2.XAML中程式碼部分

<Grid Grid.Row="3" Grid.Column="1" Name="Grid_RadioButton">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="5*"/>
                        <ColumnDefinition Width="1.66*"/>
                        <ColumnDefinition Width="1.66*"/>
                        <ColumnDefinition Width="1.66*"/>
                    </Grid.ColumnDefinitions>
                    <!--<Border Grid.Column="1" Grid.ColumnSpan="2" BorderBrush="LightBlue" BorderThickness="1"></Border>-->
                    <RadioButton Name="Rtn_Front" Grid.Column="1" IsChecked="True" Content="正面" Style="{StaticResource FontFamilyRadioButton}"></RadioButton>
                    <RadioButton Name="Rtn_Back" Grid.Column="2" Content="背面" Style="{StaticResource FontFamilyRadioButton}" ></RadioButton>
                    <TextBox HorizontalAlignment="Left" Width="250" Name="Txt_PCBNumber" Margin="1" MaxHeight="20" ></TextBox>
                </Grid>

 

3.執行結果