【问题标题】:MVVM updating LabelMVVM 更新标签
【发布时间】:2012-08-09 01:49:31
【问题描述】:

我知道这是一个经常被问到的问题,但我现在至少要一个星期才能解决它...阅读这么多线程,下载数百万个不同的 MVVM-Pattern-Examples 等等...

我只想在我的 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();
    }

完整的 ViewModel:

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 方法中设置 TextMessage 属性会引发 onPropertyChangedEvent,但不幸的是它不会更新窗口中的标签。我不知道我应该怎么做......我真的很期待帮助。提前谢谢了!

也许我应该提到 StartUpProcess_DoWork 在自己的 STAThread 中运行

亲切的问候,弗洛

【问题讨论】:

    标签: c# mvvm binding inotifypropertychanged


    【解决方案1】:

    显然,您在 GUI 线程中执行了大量工作。使用Thread.Sleep,您甚至可以暂停 GUI 线程。因此,它将无法更新控件。

    解决方案是为DoWork 方法使用不同的线程。这可以通过BackgroundWorker 轻松实现。如果您向工作人员提供 GUI 调度程序对象,您可以从那里发出 GUI 更改。尽管如果可能的话,最好使用ProgressChanged-Event。

    【讨论】:

    • 到目前为止没有其他工作或任务。计划使用启动窗口来观察加载和软件更新进度。所以我将添加有用的代码而不是 thread.sleep 函数。如果没有 Thread.sleep,我在屏幕上看不到任何消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2020-07-28
    • 2017-09-17
    • 2012-02-13
    • 2017-04-12
    相关资源
    最近更新 更多