tstanitz
tstanitz

Reputation: 111

WPF image's gotfocus/lostfocus event does not fired

Could You please help me, why GotFocus and LostFocusa event doesn't fired when I Click to image and then to textbox?

My XAML:

<Window x:Class="imageclick.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>
        <StackPanel>
            <Image Source="Untitled.png" GotFocus="GF" LostFocus="LF" Focusable="True"></Image>
            <TextBox ></TextBox>
        </StackPanel>
    </Grid>
</Window>

I could not understand why GotFocus/LostFocus event never fired

Thanks in advance

Update: When I set the tabindex, when the tab reached the image event fired, but I could not reach with mouse click

Upvotes: 2

Views: 3492

Answers (2)

Debasis
Debasis

Reputation: 458

According to MSDN, UIElement.GotFocus event occurs when this element gets logical focus.

And logical focus differs from keyboard focus, it is raised when the value of the IsFocused property of an element in the route is changed from false to true.

So, in order to achieve it through mouse clicks, need to handle the respective mouse button events or simply handle MouseDown and set the focus to the sender.

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is Image)
        {
            (sender as Image).Focus();
        }
    }

This will set the IsFocused property of the Image to true.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Image isn't a Control. Only Controls can get focus.Instead of GotFocus and LostFocus use MouseEnter and MouseLeave events,

 <StackPanel>
            <Image Stretch="Uniform" Source="Untitled.png"   Height="410" MouseEnter="Image_MouseEnter" MouseLeave="Image_MouseLeave"></Image>
            <TextBox Height="65"></TextBox>
 </StackPanel>

Upvotes: 3

Related Questions