如何检测 WPF 窗口的第一个显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16106165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:37:57  来源:igfitidea点击:

How to detect the first show of a WPF Window?

c#.netwpfwindow

提问by Daniel Pe?alba

I was wondering which is the correct way to detect when a WPF windows has been shown for the first time?

我想知道哪种方法是检测 WPF 窗口首次显示的正确方法?

回答by bash.d

There is an event called Loadedthat you can use to determine when your window is ready.

Loaded您可以使用一个名为的事件来确定您的窗口何时准备就绪。

From MSDN

来自MSDN

Occurs when the element is laid out, rendered, and ready for interaction.

在元素布局、呈现并准备好进行交互时发生。

set the handler in XAML

在 XAML 中设置处理程序

<StackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.FELoaded"
Loaded="OnLoad"
Name="root">
</StackPanel>

add the code-behind

添加代码隐藏

void OnLoad(object sender, RoutedEventArgs e)
{
    Button b1 = new Button();
    b1.Content = "New Button";
    root.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Left;
}

回答by Jeong Minu

Loaded can be called more than once.

Loaded 可以被多次调用。

The Loaded event and the Initialized event

Loaded 事件和 Initialized 事件

According to my test and the link above, Loaded event can be fired more than once.
So, you need to set a flag in the OnLoaded handler.

根据我的测试和上面的链接,可以多次触发 Loaded 事件。
因此,您需要在 OnLoaded 处理程序中设置一个标志。

For example, if Stack Panel is inside TabItem control, loaded will be called every time you step into tab.

例如,如果 Stack Panel 在 TabItem 控件内,则每次进入选项卡时都会调用加载。

回答by Postback

i would suggest to make a bool flag and check it, and in the constructor set it to true

我建议制作一个 bool 标志并检查它,并在构造函数中将其设置为 true

bool FirstTime = true;

void OnLoad(object sender, RoutedEventArgs e)
{
     if (FirstTime)
     {
          FirstTime = false;
          //do your stuff first-time
     }
     else
     {
           //do your stuff for other
     }
}