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

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

问题描述

要在 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.

推荐答案

如本文所述blog,当控件即将被呈现(即添加到可视化树)时,会触发 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.

一种解决方法是使用布尔值来标记您是否已经按照其他人的建议初始化了控件.或者,您可以使用 Initialized 事件而是.

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 用户控件的 Loaded 事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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