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 事件多次触发
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01