2

我在第一个视图(MainView)中有两个视图,我选择一个文件并将其导入,在第二个视图(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");
            });
        }         

    }

我可以做什么?

4

1 回答 1

7

您需要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");
        });
    }         

编辑:试试这个

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

        Execute.OnUIThread(() =>
        {
            WindowManager.ShowWindow(vm, null, null);
            IsBusy = false;
            NotifyOfPropertyChange("IsBusy");
            Text = "";
            NotifyOfPropertyChange("Text");
        });
    }         
于 2013-04-03T14:40:10.190 回答