2012-08-12 88 views
0

我知道這是一個經常被問到的問題,但我試圖至少在一週內解決它......閱讀了太多的線程,下載了數百萬個不同的MVVM-Pattern-Examples等。 。MVVM更新標籤

我只是想更新我的MVVM模型視圖第一種方法愚蠢的標籤:

void StartUpProcess_DoWork(object sender, DoWorkEventArgs e) 
    { 
     SplashWindow splash = new SplashWindow(); 
     var ViewModel_Splash = new VM_SplashWindow(); 
     splash.DataContext = ViewModel_Splash; 
     splash.Topmost = true; 
     splash.Show(); 
     ViewModel_Splash.DoWork(); 
    } 

完整的視圖模型:

public class VM_SplashWindow:VM_Base 
    { 
     #region Properties 
     private string _TextMessage; 
     public string TextMessage 
     { 
      get 
      { 
       return _TextMessage; 
      } 
      set 
      { 
       if(_TextMessage != value) 
       { 
        _TextMessage = value; 
        base.OnPropertyChanged("TextMessage"); 
       } 
      } 
     } 
     #endregion 

     #region Methods  
     public void DoWork() 
     { 
      this.TextMessage = "Initialize"; 
      for(int aa = 0; aa < 1000; aa++) 
      { 
       this.TextMessage = "Load Modul: " + aa.ToString(); 
       Thread.Sleep(5); 
      } 
      this.TextMessage = "Done"; 
      Thread.Sleep(1000); 
     } 
     #endregion 
    } 

從基地一小片:

public abstract class VM_Base:INotifyPropertyChanged, IDisposable 
{  
    #region INotifyPropertyChanged 
public event PropertyChangedEventHandler PropertyChanged; 

protected virtual void OnPropertyChanged(string propertyName) 
{ 
    PropertyChangedEventHandler handler = this.PropertyChanged; 
    if (handler != null) 
    { 
     var e = new PropertyChangedEventArgs(propertyName); 
     handler(this, e); 
    } 
} 
#endregion 
} 

最後認爲:

<Label Height="28" Margin="19,0,17,15" Name="label2" VerticalAlignment="Bottom" 
       Content="{Binding Path=TextMessage}" Foreground="White" /> 

如果我在視圖模型的構造函數中設置的TextMessage的一個屬性的初始值,這個初始值將在splash.Show()命令後顯示。

在DoWork-Method中設置TextMessage屬性會引發onPropertyChangedEvent,但不幸的是它不會更新窗口中的標籤。我不知道該怎麼辦......我非常期待尋求幫助。提前謝謝了!

也許我應該提到的是,StartUpProcess_DoWork是在自己的STAThread

親切的問候運行,FLO

回答

0

顯然,你是在GUI線程中執行大量的工作。與Thread.Sleep你甚至暫停GUI線程。因此,它將無法更新控件。

解決方法是爲DoWork方法使用不同的線程。這可以通過BackgroundWorker輕鬆實現。如果您將GUI分派器對象提供給worker,則可以從那裏發出GUI更改。儘管如果可能,最好使用ProgressChanged -Event。

+0

到目前爲止,沒有其他的工作或任務。計劃使用splashwindow來觀察加載和軟件更新 - 進度。所以我要添加有用的代碼而不是thread.sleep函數。沒有Thread.sleep,我在屏幕上看不到任何消息。 – Florian 2012-08-12 22:08:26