c# - 创建一个弹出窗口的正确方法是什么,该窗口包含一个仅在第一次加载到 WPF 项目时才执行的方法?
问题描述
在我的项目中,我在弹出窗口中有一个方法。这个方法应该只在第一次加载弹出窗口时执行。也就是说,当我多次打开窗口时,该方法只在第一轮运行。实施它的正确方法是什么?
代码说明如下:
- 表单有一个组合框
- comboBox.SelectedValueChanged 与方法 ApplyPropertyGrid 相关联:
this.comboBoxEx1.SelectedValueChanged += ApplyPropertyGrid;
MyMethod
在方法 ApplyPropertyGrid 中,有一个只需要执行一次的子方法:
private void ApplyPropertyGrid(object sender, EventArgs e) {...... ...... MyMethod() ......}
解决方案
一个Lazy
代表被保证只触发一次。即使您的应用程序是多线程的。
一个问题是你必须返回一些东西,尽管你可以把结果扔掉。在我的示例中,MyMethod
只需返回true
.
如果将其设为静态,则该特定表单的所有实例只会加载一次。
为了确保您的 ApplyPropertyGrid 方法已运行,只需获取其值即可。
class MyForm : Form
{
static Lazy<bool> _runOnce = new Lazy<bool>(MyMethod);
static bool MyMethod()
{
Console.WriteLine("This will run only once!");
return true;
}
private void ApplyPropertyGrid(object sender, EventArgs e)
{
bool isInitialized = _runOnce.Value;
//You can be sure at this point that MyMethod has executed exactly once
}
推荐阅读
- sql - 用于在同一列的连续行中查找不同记录的 SQL 查询
- html - Flexbox 中的 CSS 网格突然中断
- excel - Excel If 或 Vlookup 以查看值是否等于 2 或 3
- sql - FOREIGN KEY 约束失败,SQLite
- python - 使用 tensorflow 数据集对象训练两个输入模型
- reactjs - 我有一个带有搜索栏的简单信使应用程序,每当我按退格键时,它都不会更新过滤器
- javascript - 如何将 HTML 表中的选定行发送到烧瓶并呈现新模板?
- python-3.x - 如果满足多个条件,如何将列的值设置为等于另一列?
- python - 如何将字典中的值与数字相乘以获得实际值?
- graphql - 即使是客户端错误,graphql 服务器是否总是返回 500?