首页 > 解决方案 > 创建一个弹出窗口的正确方法是什么,该窗口包含一个仅在第一次加载到 WPF 项目时才执行的方法?

问题描述

在我的项目中,我在弹出窗口中有一个方法。这个方法应该只在第一次加载弹出窗口时执行。也就是说,当我多次打开窗口时,该方法只在第一轮运行。实施它的正确方法是什么?

代码说明如下:

  1. 表单有一个组合框
  2. comboBox.SelectedValueChanged 与方法 ApplyPropertyGrid 相关联: this.comboBoxEx1.SelectedValueChanged += ApplyPropertyGrid;
  3. MyMethod在方法 ApplyPropertyGrid 中,有一个只需要执行一次的子方法:

private void ApplyPropertyGrid(object sender, EventArgs e) {...... ...... MyMethod() ......}

标签: c#wpf

解决方案


一个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
    }

推荐阅读