C# 更新线程中不同类的UI元素
我正在尝试更新线程中不同类的UI表单 有关守则如下: MainWindow.xaml.csC# 更新线程中不同类的UI元素,c#,wpf,multithreading,C#,Wpf,Multithreading,我正在尝试更新线程中不同类的UI表单 有关守则如下: MainWindow.xaml.cs private void encryptButtonPressed(object sender, RoutedEventArgs e) { if (checkValues() == true) { updateConsole("Starting Encryption..."); Thread encryptThread = new Thread(encry
private void encryptButtonPressed(object sender, RoutedEventArgs e)
{
if (checkValues() == true)
{
updateConsole("Starting Encryption...");
Thread encryptThread = new Thread(encrypt);
encryptThread.Start();
}
}
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 encrypt()
{
Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
encrypt.start();
}
public void start()
{
mainWindow.updateConsole("Updating form thread");
}
更新控制台功能
public void updateConsole(String text)
{
consoleWindow.AppendText(Environment.NewLine);
consoleWindow.AppendText(text);
consoleWindow.ScrollToEnd();
}
加密.cs
private void encryptButtonPressed(object sender, RoutedEventArgs e)
{
if (checkValues() == true)
{
updateConsole("Starting Encryption...");
Thread encryptThread = new Thread(encrypt);
encryptThread.Start();
}
}
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 encrypt()
{
Encrypt encrypt = new Encrypt(this.KeyFileContent, this.SourcePath, this.DestinationPath, this);
encrypt.start();
}
public void start()
{
mainWindow.updateConsole("Updating form thread");
}
我试过了
Dispatcher.Invoke(() =>
{
mainWindow.updateConsole("Updating form thread");
});
但是没有用。你应该只传递你需要的东西,而不是注入整个
主窗口。在本例中,使用updateConsole方法
将启动方法更改为:
public void start(Action<string> updateConsole)
{
updateConsole.Invoke("Updating form thread");
}
最后,您不再需要将main窗口中的注入加密类:
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;
}
但没有用。
这是什么意思?这意味着我最后尝试的东西不起作用。你说的“不起作用”是什么意思?您是否没有看到任何内容、错误、崩溃?即使使用Dispatcher.Invoke
,您是否也会收到异常?错误是什么?我尝试了Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,新操作(()=>this.mainWindow.updateConsole))这是一个精心设计的解决方案,但目前,我的代码正在运行:)。我会保留它以备将来参考。谢谢:)我还注意到您没有使用数据绑定到控制台Windows
。如果这是一个更大的项目,也许您应该读懂MVVM:-)这只是一个小项目。谢谢你的建议:)而且我是初学者