2013-04-03 31 views
2

我在第一個視圖(MainView)中選擇一個文件並導入它,在第二個視圖(BView)中顯示該文件在數據網格中的詳細信息。在新任務中打開另一個視圖WPF caliburn.micro c#

這是第一個觀點(的MainView):

enter image description here

這是第二個觀點(BView):我想,當我點擊 「導入」 就出現 enter image description here

進度條和文本,而第二個視圖加載。我想打開另一個任務中的另一個視圖,但我收到此錯誤消息:

「調用線程無法訪問此對象,因爲不同的線程擁有它。」

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

    } 

我能做些什麼?

+0

難道是用'WindowManager.ShowWindow'不是在UI線程上做什麼?看起來其他所有內容都被編組到UI線程 - 哪一行會引發錯誤? – Charleh

+0

This line:WindowManager.ShowWindow(new BViewModel(Path),null,null); – puti26

回答

5

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

好的。這行得通 !但爲什麼現在進度欄是可見的,但不移動? – puti26

+0

當你創建它時,你的新視圖模型會做很多工作嗎? – Charleh

+0

由於您沒有發佈B視圖模型代碼,因此我只能假設當您創建此視圖模型時,它會執行一些導入數據的工作,但是您正在ui線程中創建您的工作。你需要進程然後顯示虛擬機,而不是做在UI線程 – Charleh

相關問題