WPF 用户控件的 Loaded 事件多次触发

Loaded event of a WPF user control fires more than once(WPF 用户控件的 Loaded 事件多次触发)
本文介绍了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 事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)