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

put*_*i26 2 c# wpf view caliburn.micro

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

这是第一个视图(MainView):

在此输入图像描述

这是第二个视图(BView): 在此输入图像描述

我希望当我单击"导入"时出现在进度条和文本上,而第二个视图加载时.我想在另一个TASK中打开另一个视图,但是我收到此错误消息:

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

这是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");
            });
        }         

    }
Run Code Online (Sandbox Code Playgroud)

我可以做什么?

Cha*_*leh 6

您需要WindowManager.ShowWindow在UI线程上执行,因为Task.Start()将位于不同的线程上.任何UI操作应该总是被整理到UI线程或者你得到你所提到的跨线程异常.

尝试:

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

编辑:试试这个

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

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