0

次のXAMLがあります

<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 つのボタンが縦に並んだダイアログ ボックスを生成します。ボタンの 1 つをクリックすると、メッセージ ボックスに [OK] ボタンが表示されます。しかし、ダイアログ ボックスの [OK] ボタンは、2 回クリックしないと閉じません。上記のコードから暗黙的にこれを行いましたか?

編集 - 追加情報:

代わりにこれを行うと

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

        }

..メッセージ ボックスを閉じるには、2 回クリックする必要があります。

4

1 に答える 1

3

あなたの問題は、ハンドラーを2倍にしていることです。同じ を 2 回クリックする必要はありませんOK。[OK] をクリックすると、最初のメッセージが閉じます。次に、イベントが再度処理され、まったく同じメッセージが表示されます。このメッセージに対して [OK] をクリックする必要があります。メッセージに追加+ DateTime.Nowすると、これが実際に 2 番目のメッセージであることがわかります。

最初に見たとき、次の行を見逃していました。

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

ButtonBase.Clickこの行の と同じです

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

イベント ハンドラーにアタッチする方法を 1 つ選択し、それに固執します。それらを混同すると、混乱が生じるだけです。

于 2013-02-15T20:40:45.140 に答える