Loaded event of a WPF user control fires more than once(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 事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WPF 用户控件的 Loaded 事件多次触发
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
