开发者

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:

  • I have 3 buttons: A, B and C
  • "Button A" has focus
  • "Button C" is clicked
  • "Button A" LostFoc开发者_运维问答us 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!


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜