gpt4 book ai didi

c# - UI 线程未按预期刷新为 WPF 表单

转载 作者:行者123 更新时间:2023-11-30 20:34:46 26 4
gpt4 key购买 nike

我在此 RelayCommand 中遇到 UI 刷新问题:

private RelayCommand _DeleteReferenceCommand;
public RelayCommand DeleteReferenceCommand
{
get
{
return _DeleteReferenceCommand ?? (_DeleteReferenceCommand = new RelayCommand(
() =>
{
//the 2 next lines trigger properties that will modify some components Visibility on the view
ReferencesGridWithPicsUC.TextReplacingGridView = "Deleting the reference. Please wait...";
ReferencesGridWithPicsUC.GridViewVisibility = false;
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; // mouse cursor change


//using multi-threading so that UI updates while a long process takes place in the background
Task.Run(() =>
{
Application.Current.Dispatcher.Invoke((new Action(() =>
{
System.Threading.Thread.Sleep(3000); // simulates a long process
ReferencesGridWithPicsUC.GridViewVisibility = true; // Sets the UI controls visibility back to previous state
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Hand; // Mouse cursor back to previous value
}
)));
}
);
},
() => { return ReferencesGridWithPicsUC.SelectedReference != null; }
));
}
}

具体来说,当我启动应用程序并首次运行此代码时,它按预期工作(鼠标光标和控件在 Sleep(3000) 之前按预期更新,之后恢复正常。再次执行代码时,我可以看到该属性已正确更新 GridViewVisibility 。但 UI 不再刷新:由 GridViewVisibility 更改触发的控件可见性未更新。另一方面,鼠标光标按预期不断更新....

如果有人能解开这个该死的谜题,那我就欠你的了;)

最佳答案

您必须调用 Dispatcher 来更新 UI。

为后台任务使用Task.Run

await Task.Run(() =>
{
Thread.Sleep(3000);
});

在异步委托(delegate)中

new RelayCommand(
async () =>
{

之后,您将回到 UI 线程中,因此不再需要 Dispatcher。

关于c# - UI 线程未按预期刷新为 WPF 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com