sturdytree
sturdytree

Reputation: 859

Seemingly strange WPF behaviour: textbox lostfocus event and button click event

The following behaviour is occurring with the .net 4.0 code set out further below:

Click on textbox so it gains focus, and then click button:

  1. As code stands, lostfocus handler is called, but not buttonclick handler
  2. Comment out MessageBox.Show("handlelostfocus") and then click handler is called
  3. Set breakpoint in handlelostfocus and breakpoint is hit, but click handler is not called

Are these bugs or behaviour by design - if later, is there any further explanation?

<Window x:Class="WpfApplication4.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="216,194,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="197,108,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
        </Grid>
    </Window>

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            textBox1.LostFocus += new RoutedEventHandler(handlelostfocus);
        }

        private void handlelostfocus(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("handlelostfocus");
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("click");
        }
    }

Upvotes: 0

Views: 1787

Answers (3)

Gaurav Khanna
Gaurav Khanna

Reputation: 31

Change ClickMode property of Button to "Press"

<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="216,194,0,0" ClickMode="Press" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" MouseUp="button1_MouseUp" MouseLeftButtonUp="button1_MouseLeftButtonUp" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="197,108,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />

Upvotes: 3

Jon
Jon

Reputation: 2891

The 'click' in this case never occurs because as H.B. indicated you are interrupting the UI/event logic by showing the modal messagebox so there is never a mouse down event on the button.

Try replacing the messagebox with a non-modal wndow such as this: new Window() { Width = 300, Height = 100, Title = "handlelostfocus" }.Show();

and you will see that the events still occur because you are not drawing the focus away from the main window in the middle of the event logic.

Upvotes: 2

brunnerh
brunnerh

Reputation: 184376

You interrupt the click logic, to get a click both mouse-down and its mouse-up need to occur consecutively on the Button; thus the observed behavior seems fine to me.

Upvotes: 1

Related Questions