c# - WPF MVVM 短时间显示标签文本
问题描述
我的Label
视图中有一个状态栏中,我用它向用户显示消息。我只想显示消息并更改背景颜色几秒钟,这样我就不必使用额外的代码行来清除标签。
我在视图模型中有一个StatusText
和StatusColor
属性,标签内容和颜色绑定到这些,并且工作正常。
我的问题是如何在 ViewModel 中计时?
我可以在 viewmodel 方法中使用计时器,并且在显示消息时不会冻结 UI 吗?
我正在尝试遵守 MVVM 框架,但在不使用事件的情况下我无法在 SO 上找到任何解决方案。有可能以某种简单的方式吗?
解决方案
使用命令而不是事件。Command 将在 ViewModel 中找到名称匹配的 ICommand 属性。这将使您的视图和代码隐藏分离。
在xml中
<Button Command="ChangeColorCommand" />
在 ViewModel 注意:
timer
是System.Timers.Timer
. 我跳过了它的实例化代码。
TimerTicked
timer
在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的实现可以参考这篇文章
推荐阅读
- python - 如何为数据框中的两个特定列选择两个数字之间的值以绘制为二维图
- python - 无法将 Twilio Python SDK 响应对象序列化为简单的 dict 对象
- javascript - 如何访问Nodejs中两个数组内的对象?
- vue.js - 错误:通过导航守卫从“/”转到“/dashboard”时重定向
- python - 熊猫在索引 0 处添加行
- apache-flink - Flink Heap 内存泄漏?
- kotlin - 为什么 Kotlin 不能选择使用哪个重载函数?
- sqlite - 使用 JetBrains IDE WebStorm,我如何使用 SQL DDL 创建数据库,(具有“访问被拒绝。”错误)
- tensorflow - tf.data WindowDataset flat_map 给出 'dict' 对象没有属性 'batch' 错误
- python-3.x - 使用 Fipy 表示动量方程的项时遇到问题