gpt4 book ai didi

c# - 在新任务中打开另一个 View WPF caliburn.micro c#

转载 作者:行者123 更新时间:2023-12-03 22:59:37 24 4
gpt4 key购买 nike

我在第一个 View (MainView)中有 2 个 View ,我选择一个文件并导入它,在第二个 View (BView)中,在数据网格中显示该文件的详细信息。

这是第一个 View (MainView):

enter image description here

这是第二个 View (BView): enter image description here

我希望当我单击“导入”时,进度条和文本会出现,同时加载第二个 View 。我想在另一个任务中打开另一个 View ,但我收到此错误消息:

“调用线程无法访问此对象,因为另一个线程拥有它。”

这是 MainViewModel 的代码是:

[Export(typeof(IShell))]
public class MainViewModel : Screen
{
public string Path{ get; set; }
public bool IsBusy { get; set; }
public string Text { get; set; }
[Import]
IWindowManager WindowManager { get; set; }

public MainViewModel()
{
IsBusy = false;
Text = "";
}


public void Open()
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "Text|*.txt|All|*.*";
fd.FilterIndex = 1;

fd.ShowDialog();

Path= fd.FileName;
NotifyOfPropertyChange("Path");
}


public void Import()
{
if (Percorso != null)
{
IsBusy = true;
Text = "Generate..";
NotifyOfPropertyChange("IsBusy");
NotifyOfPropertyChange("Text");
Task.Factory.StartNew(() => GoNew());

}
else
{
MessageBox.Show("Select file!", "Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}

public void GoNew()
{
WindowManager.ShowWindow(new BViewModel(Path), null, null);
Execute.OnUIThread(() =>
{
IsBusy = false;
NotifyOfPropertyChange("IsBusy");
Text = "";
NotifyOfPropertyChange("Text");
});
}

}

我能做什么?

最佳答案

您需要在 UI 线程上执行 WindowManager.ShowWindow,因为 Task.Start() 将在不同的线程上。任何 UI 操作都应始终编码到 UI 线程,否则会出现您提到的跨线程异常。

尝试:

    public void GoNew()
{
Execute.OnUIThread(() =>
{
WindowManager.ShowWindow(new BViewModel(Path), null, null);
IsBusy = false;
NotifyOfPropertyChange("IsBusy");
Text = "";
NotifyOfPropertyChange("Text");
});
}

编辑:试试这个

   public void GoNew()
{
var vm = new BViewModel(Path);

Execute.OnUIThread(() =>
{
WindowManager.ShowWindow(vm, null, null);
IsBusy = false;
NotifyOfPropertyChange("IsBusy");
Text = "";
NotifyOfPropertyChange("Text");
});
}

关于c# - 在新任务中打开另一个 View WPF caliburn.micro c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15782861/

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