2013-02-15 61 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