繁体   English   中英

如何在 WPF 表格外部调用 function

[英]How to call a function inside a WPF form outside of it

这是我正在尝试访问的 window 内部的 function

public void LogConsole(string message, string type = "Default")
{
    Thread LogConsoleThread = new Thread(() =>
    {
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            ConsoleLogBox.Text += $"{Environment.NewLine}[{DateTime.Now.ToString("h:mm:ss tt")}] {message}";
        }));

    });
    LogConsoleThread.Start();

    ConsoleLogBox.ScrollToEnd();
}

这是 function 试图访问它的主窗口之外

public static void LogConsole(string message, string type = "Default")
{
    Application.Current.Dispatcher.Invoke(new Action(() =>
    {
        ((MainWindow)Application.Current.MainWindow).LogConsole(message, type);
    }));
}

在我添加另一个我制作启动表单的表单之前,此代码正在运行。 因此,当 MainWindow 表单不再是启动表单时,我收到错误“System.NullReferenceException:'对象引用未设置为 object 的实例。'”我假设是因为它现在正在尝试访问启动表单尽管此代码仅在 MainWindow 窗体是唯一打开的窗体时才运行,所以我不确定如何编辑它。

我知道我可以使用 MVVM,尽管对于这个项目我不能使用 MVVM,因为为时已晚。 所以我不能使用 MVVM。

在您的MainWindow class 中,添加以下内容:

public static MainWindow Instance;

public MainWindow()
{
    InitializeComponent();
    Instance = this;
}

将您的static “外部”方法更改为:

public static void LogConsole(string message, string type = "Default")
{
    Application.Current.Dispatcher.Invoke(new Action(() =>
    {

        if (MainWindow.Instance != null)
        {
            (MainWindow.Instance.LogConsole(message, type)
        }
        else
        {
            //Do something if MainWindow isn't loaded yet
        }
    }));
}

并将您的“内部”方法更改为:

public void LogConsole(string message, string type = "Default")
{            
    ConsoleLogBox.Text += $"{Environment.NewLine}[{DateTime.Now.ToString("h:mm:ss tt")}] {message}";
    ConsoleLogBox.ScrollToEnd();
}

请注意,我已经删除了新线程的创建,因为您所做的只是创建一个新线程以立即再次调用 UI 线程,这是没有意义的。
对于static版本,除非您打算从另一个线程调用它,否则您可以删除Dispatcher.Invoke 我把它留了以防万一。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM