Windows.Activated 在 wpf 中触发多次

Windows.Activated in wpf fires multiple times

您好,我有一段代码要在 window(WPF window) 激活时编写,例如单击 window 或使用 alt/tab。 window 是主窗体(windows 应用程序)的子窗体。我使用 ToolWindow 作为 windows 样式。

它有一个必须在激活时更新的 xamdatagrid

问题是它触发了多次。它应该被解雇一次。我不希望我的代码 运行 多次

如何让它发挥作用。请帮忙

来自 MSDN 上的 Window.Activated Event 页面:

Occurs when a window becomes the foreground window.

Window.Activated 事件应该 被多次调用,所以它可能不是您处理的最佳事件。或者,您可以添加一个 bool isFirstTime 变量并使用它来限制您的代码只被调用一次。举个例子:

private bool isFirstTime = true;

...

private void WindowActivated(object sender, EventArgs e)
{
    if (isFirstTime)
    {
        isFirstTime = false;
        // do something here just once
    }
}

然而,作为(来自链接页面)...

A window is activated (becomes the foreground window) when:

• The window is first opened.
• A user switches to a window by selecting it with the mouse, pressing ALT+TAB, or from Task Manager.
• A user clicks the window's taskbar button.

...您可能会发现这对您不起作用。

我搞定了。 我正在使用下面的代码

 private void OnAttributeHistoryWindowActivated(object sender, EventArgs e)
 {
        var win = ((RoutedEventArgs)(e)).Source as AttributeHistoryWindow;
       //My Code
 }

第一行代码触发了 Activated 事件。而且它永远不会进入我的代码的下一行。

现在我使用了下面的代码并且它有效。

 private void OnAttributeHistoryWindowActivated(object sender, EventArgs e)
 {
       var win = sender as AttributeHistoryWindow;
       //My Code
 }

现在触发一次。