【问题标题】:Update UI element of different class from a thread从线程更新不同类的 UI 元素
【发布时间】:2018-04-26 11:57:02
【问题描述】:

我正在尝试更新线程内不同类的 UI。

相关代码为:

MainWindow.xaml.cs

private void encryptButtonPressed(object sender, RoutedEventArgs e)
{
    if (checkValues() == true)
    {
        updateConsole("Starting Encryption...");

        Thread encryptThread = new Thread(encrypt);
        encryptThread.Start();
    }
}

加密函数

public void encrypt()
{
    Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
    encrypt.start();
}

更新控制台功能

public void updateConsole(String text)
{
    consoleWindow.AppendText(Environment.NewLine);
    consoleWindow.AppendText(text);

    consoleWindow.ScrollToEnd();
}

Encrypt.cs

public byte[] key;
public String source;
public String destination;
public MainWindow mainWindow;

public Encrypt(byte[] key, String source, String destination, MainWindow mainWindow) 
{
    this.key = key;
    this.source = source;
    this.destination = destination;
    this.mainWindow = mainWindow;
}

启动函数

public void start()
{
    mainWindow.updateConsole("Updating form thread");
}

我试过了

Dispatcher.Invoke(() =>
    {
        mainWindow.updateConsole("Updating form thread");
    });

但没用。

【问题讨论】:

  • but no use. 是什么意思?
  • 这意味着我尝试的最后一件事不起作用。
  • “不起作用”是什么意思?你什么也没看到,一个错误,它崩溃了吗?
  • 即使使用Dispatcher.Invoke 也会出现异常吗?错误是什么?
  • 我已经尝试Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => this.mainWindow.updateConsole(s))); 并且它正在工作。

标签: c# wpf multithreading


【解决方案1】:

你应该只传递你需要的东西,而不是注入整个 mainWindow。在本例中为 updateConsole 方法。

把启动方法改成这样:

public void start(Action<string> updateConsole)
{
    updateConsole.Invoke("Updating form thread");
}

那么你应该可以通过这样的方法:

public void encrypt()
{
    Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
    start(updateConsole);
}

最后,您不再需要将 mainWindow 注入到您的 Encrypt 类中:

public byte[] key;
public String source;
public String destination;

public Encrypt(byte[] key, String source, String destination) 
{
    this.key = key;
    this.source = source;
    this.destination = destination;
}

【讨论】:

  • 这是一个精心设计的解决方案,但目前我的代码正在运行:)。我会保留它以供将来参考。谢谢:)
  • 另外我注意到你没有使用数据绑定到你的consoleWindow。如果这是一个更大的项目,也许你应该阅读 MVVM :-) MVVM
  • 这只是一个小项目。谢谢你的建议:)
  • 加上我是初学者
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 2013-07-26
  • 1970-01-01
  • 2014-05-11
相关资源
最近更新 更多