Carlo
Carlo

Reputation: 25969

Get element that stole focus before it does in WPF

To be clearer. I need to know which element stole focus in the focused element LostFocus event. Something like this:

Let me know if there's a way to accomplish this.

Thanks!

Upvotes: 2

Views: 3065

Answers (1)

ASanch
ASanch

Reputation: 10383

You can always check the FocusManager.GetFocusedElement(dObj) to get the focused element within a given DependencyObject. So, in your scenario above, it will be something like this:

<Window x:Class="WpfApplication1.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">
    <Window.Resources>
        <Style TargetType="Button">
            <EventSetter Event="LostFocus" Handler="OnLostFocus"/>
        </Style>
    </Window.Resources>

    <StackPanel>
        <Button>Button1</Button>
        <Button>Button2</Button>
        <Button>Button3</Button>
    </StackPanel>
</Window>

Event Handler:

private void OnLostFocus(object sender, RoutedEventArgs e)
{
    object focusedElement = FocusManager.GetFocusedElement(this);

    if (focusedElement is Button)
        Console.WriteLine(((Button)focusedElement).Content.ToString());
}

Upvotes: 4

Related Questions