我正在尝试更新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");
});
但没有用。
答案 0 :(得分:1)
而不是注入整个mainWindow
,你应该只传递你需要的东西。在这种情况下,updateConsole方法。
将start方法更改为:
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
注入您的加密课程了:
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;
}