我正在尝试调试丢失/额外制表位的一些问题。我可以附加某种全局事件,以便在焦点发生变化时我可以记录哪个元素得到了焦点吗?谢谢!这就是我现在正在做的事情,它运作良好,但我仍然对是否有另一种方式感到好奇:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.2);
timer.Tick += onTick;
timer.Start();
// ...
private object LastFocusedElement;
private void onTick(object sender, EventArgs e)
{
object elem = FocusManager.GetFocusedElement();
if(LastFocusedElement != elem)
{
LastFocusedElement = elem;
System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
}
}
答案 0 :(得分:2)
您应该可以为“最顶层”容器订阅GotFocus
事件。我没有看到RoutedEventArgs
的任何Handled标志,所以据我所知,它应该始终达到它
<UserControl ...
GotFocus="UserControl_GotFocus">
<!-- Lots of Nested Controls -->
</UserControl>
private void UserControl_GotFocus(object sender, RoutedEventArgs e)
{
object elem = e.OriginalSource;
System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
}
答案 1 :(得分:-1)
您应该可以使用AddHandler函数将焦点事件与控件挂钩。
查看AddHandler签名,即使已经处理了一个事件,您也应该能够收到通知。