首页 > 解决方案 > WPF MVVM 短时间显示标签文本

问题描述

我的Label视图中有一个状态栏中,我用它向用户显示消息。我只想显示消息并更改背景颜色几秒钟,这样我就不必使用额外的代码行来清除标签。

我在视图模型中有一个StatusTextStatusColor属性,标签内容和颜色绑定到这些,并且工作正常。

我的问题是如何在 ViewModel 中计时?

我可以在 viewmodel 方法中使用计时器,并且在显示消息时不会冻结 UI 吗?

我正在尝试遵守 MVVM 框架,但在不使用事件的情况下我无法在 SO 上找到任何解决方案。有可能以某种简单的方式吗?

标签: c#wpfmvvm

解决方案


使用命令而不是事件。Command 将在 ViewModel 中找到名称匹配的 ICommand 属性。这将使您的视图和代码隐藏分离。

在xml中

<Button Command="ChangeColorCommand" />

在 ViewModel 注意: timerSystem.Timers.Timer. 我跳过了它的实例化代码。

TimerTickedtimer在Elapsed时调用。

您不必使用DispatcherTimer,因为StatusText并且StatusColor不是 UI 对象。

    public ICommand ChangeColorCommand
    {
        get
        {
            return new RelayCommand( ChangeColorAndMessage );
        }
    }
    // This is your view model constructor
    private void ViewModelCtor(){
       // your initialize code here

        //subscribe event once
        timer = new Timer();
        timer.Interval=1000;
        timer.AutoReset=false;
        timer.Elapsed += TimerTicked;
    }

    public void ChangeColorAndMessage( string[] args )
    {
        StatusText = "Button pressed";
        StatusColor = changedColor;

        // You implementation for changing it back.
        timer.Enabled = true;
    }

    private void TimerTicked( object sender, EventArgs e )
    {
        StatusText = "origin";
        StatusColor = originColor;

        // Fire property changed to notify view updating data.
        PropertyChanged( this, new PropertyChangedEventArgs( StatusText ) );
        PropertyChanged( this, new PropertyChangedEventArgs( StatusColor ) );
    }

RelayCommand的实现可以参考这篇文章


推荐阅读