更清楚。我需要知道哪个元素在聚焦元素LostFocus事件中占据了焦点。像这样:
让我知道是否有办法实现这一目标。
谢谢!
答案 0 :(得分:4)
您始终可以检查FocusManager.GetFocusedElement(dObj)以获取给定DependencyObject中的焦点元素。因此,在上面的场景中,它将是这样的:
<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>
事件处理程序:
private void OnLostFocus(object sender, RoutedEventArgs e)
{
object focusedElement = FocusManager.GetFocusedElement(this);
if (focusedElement is Button)
Console.WriteLine(((Button)focusedElement).Content.ToString());
}