2013-02-15 158 views
0

我已在XAML附事件WPF:OK按鈕總是需要2次點擊關閉

<Window x:Class="SimpleAttahEvent.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow"> 
    <Grid> 
     <StackPanel Margin="5" Name="stackButton" ButtonBase.Click="DoSomething"> 
      <Button Name="cmd1" Tag="The first button"> Command 1</Button> 
      <Button Name="cmd2" Tag="The second button"> Command 2</Button> 
      <Button Name="cmd3" Tag="The third button"> Command 3</Button> 

     </StackPanel> 
    </Grid> 
</Window> 

下......用下面的代碼來處理連接的事件。

namespace SimpleAttahEvent 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 

     public MainWindow() 
     { 
      InitializeComponent(); 
      stackButton.AddHandler(Button.ClickEvent, new RoutedEventHandler(DoSomething)); 
     } 

     private void DoSomething(object sender, RoutedEventArgs e) 
     { 
      Console.WriteLine(Button.ClickEvent.RoutingStrategy); 
      Console.WriteLine(TextBox.PreviewKeyDownEvent.RoutingStrategy); 
      if (e.Source == cmd1) 
      { 
       MessageBox.Show("First button is clicked"); 
      } 
      if (e.Source == cmd2) 
      { 
       MessageBox.Show("Second button is clicked"); 
      } 
      if (e.Source == cmd3) 
      { 
       MessageBox.Show("Third button is clicked"); 
      } 


     } 
    } 
} 

這些產生一個3個垂直堆疊按鈕的對話框。當我點擊其中一個按鈕時,一個消息框出現一個OK按鈕。但是,除非我點擊了兩次,否則對話框上的確定按鈕將不會關閉。我是否從上面給出的代碼隱含地做到這一點?

編輯 - 附加信息:

當我做到這一點,而不是

private void DoSomething(object sender, RoutedEventArgs e) 
     { 
      object tag = ((FrameworkElement)sender).Tag; 
      MessageBox.Show((string)tag); 

     } 

..它仍然需要2次點擊關閉該消息框。

+1

這適用於我。有沒有其他可能與此功能交互的代碼? – 2013-02-15 20:46:49

+0

這些都是我擁有的。我想不出任何會與此功能交互的其他東西。 – ikel 2013-02-15 20:55:13

+0

如何在沒有路由事件處理程序的情況下嘗試它?只需在每個按鈕中定義點擊處理程序即可作爲測試。 – EJA 2013-02-15 20:58:07

回答

3

你的問題是你正在加倍你的處理程序。您不必在同一個OK上點擊兩次;你點擊確定,關閉第一條消息。然後,再次處理該事件,並獲得另一個完全相同的消息,您必須單擊確定。如果添加+ DateTime.Now到您的郵件,你會看到,這確實是一個第二消息

我錯過了我乍一看這條線:

stackButton.AddHandler(Button.ClickEvent, new RoutedEventHandler(DoSomething)); 

這是一樣的ButtonBase.Click從該行

<StackPanel Margin="5" Name="stackButton" ButtonBase.Click="DoSomething"> 

選擇一種方法附加到事件處理程序並堅持下去。把它們混合起來會引起混淆。

+1

啊!感謝您指出!我把它叫了兩次。 – ikel 2013-02-18 07:00:07