views:

19

answers:

1

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

  • I have 3 buttons: A, B and C
  • "Button A" has focus
  • "Button C" is clicked
  • "Button A" LostFocus event is triggered
  • In there I want to know that "Button C" stole the focus (Could've also been "Button B")

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

Thanks!

+3  A: 

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());
}
karmicpuppet