WPF用户控件的已加载事件触发多次 [英] Loaded event of a WPF user control fires more than once

查看:444
本文介绍了WPF用户控件的已加载事件触发多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 WPF 中实现基于选项卡的环境,我们需要将表单转换为用户控件,但是在执行此操作时,会发生 Loaded 事件用户控件的名称被称为两次

To implement a tab-based environment in WPF we need to convert our forms to user controls, however when doing this, the Loaded event of the user control is called two times.

在互联网上搜索时,其他人也指出了这个问题。我们如何确保已加载事件仅被调用一次?因为当多次调用它时,我们的控件的初始化会发生多次。

While searching on the internet other people also pointed this issue. How can we ensure that loaded event is called only once? Because when it is called multiple times, initialization of our controls happens multiple times.

推荐答案

如本博客,当控件要执行以下操作时,就会触发Loaded事件

As explained in this blog, the Loaded event is fired when ever a control is about to be rendered (i.e. added to the visual tree).

有几个控件会导致您的控件被多次加载/卸载。例如,本机WPF TabControl仅呈现所选选项卡的内容。因此,当您选择一个新选项卡时,先前选择的选项卡的内容将被卸载。如果您单击返回到先前选择的选项卡,则会重新加载其内容。

There are several controls that would cause your control to be loaded/unloaded multiple times. For example, the native WPF TabControl only renders the content of the selected tab. So when you select a new tab, the content of the previously selected tab is unloaded. If you click back to the previously selected tab, then it's content is reloaded.

一种解决方法是使用布尔值来标记您是否已初始化控件,例如由其他人建议。或者,您可以使用已初始化事件代替。

One work around is to use a Boolean to flag whether you have already initialized your control, as suggested by others. Alternatively, you may be able to use the Initialized event instead.

这篇关于WPF用户控件的已加载事件触发多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆