2012-08-12 91 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