当前位置: 首页 > news >正文

WPF-MVVM计数器

简单的计数案例,ViewModel开启辅助线程,模拟后端运行,该方式可以扩展为项目中的后端线程数采及运算呈现,便于实时监控数据的场景。

代码如下:

MyCommand

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MVVMCountDemo.ViewModel
{
    public class MyCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public MyCommand(Action execute, Func<bool> canExecute = null)
        {

            _execute = execute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute();
        }

        public void Execute(object parameter)
        {
            _execute();
        }



    }
}

Notify  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace MVVMCountDemo.ViewModel
{
    public abstract class Notify : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

    }
}

Window.xaml

<Window x:Class="MVVMCountDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MVVMCountDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label  FontSize="30" Content="{Binding Seconds}"   Foreground="Black" HorizontalAlignment="Left" Margin="141,85,0,0" VerticalAlignment="Top" Height="110" Width="230"/>
        <Button Content="开始/清零" HorizontalAlignment="Left" Margin="203,224,0,0" VerticalAlignment="Top" Width="100" Command="{Binding StartOrResetCommand}"/>
    </Grid>
</Window>

MainWindow.cs

using MVVMCountDemo.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MVVMCountDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new CountDemoViewModel();
        }
    }
}

CountDemoViewModel 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;

namespace MVVMCountDemo.ViewModel
{
    public class CountDemoViewModel:Notify
    {

        private DispatcherTimer timer;
        private int seconds = 0;

        public int Seconds
        {
            get { return seconds; }
            set
            {
                if (seconds != value)
                {
                    seconds = value;
                    OnPropertyChanged(nameof(Seconds));
                }
            }
        }


        public ICommand StartOrResetCommand { get; private set; }

        public CountDemoViewModel()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
            StartOrResetCommand = new MyCommand(StartOrReset);
        }

        int currentCount = 0;
        int lastCount = 0;

        private void Timer_Tick(object sender, EventArgs e)
        {
            currentCount++;
            Seconds = currentCount - lastCount;
        }




        private void StartOrReset()
        {
            if (timer.IsEnabled)
            {
                timer.Stop();
                Seconds = 0;
                lastCount = currentCount;
            }
            else
            {
                timer.Start();
            }
        }

    }
}

相关文章:

  • 华为供应链的变革模式和方法P105(105页PPT)(文末有下载方式)
  • MySQL中的事务隔离级别有哪些
  • 【MySQL】基础查询
  • xLua_001
  • AIAgent有哪些不错的开源平台
  • 每天看一篇漏洞报告
  • R语言入门课| 02 R及Rstudio的下载与安装
  • 类加载器及双亲委派机制
  • vscode vue3 jsconfig 与 tsconfig的区别
  • Vue渲染函数 - render 函数
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring Boot 的起步依赖:快速构建 JavaWeb 项目
  • vscode记录
  • SQL注入中空格与逗号过滤的绕过技巧总结
  • PHP、Java、Go、Python、Node.js、Ruby 写的接口,服务器承载量对比
  • 爬虫逆向:详细讲述iOS底层原理及机制
  • 健康养生:为生命注入活力
  • k8s基础资源管理指令
  • freeswitch (中继网关呼出配置)
  • VSCode - 查看 PDF 文件
  • 信息学奥赛一本通 1526:Blockade | 洛谷 P3469 [POI 2008] BLO-Blockade
  • 复旦大学艺术馆开馆:以当代视角再看文科文脉
  • 男子聚餐饮酒后身亡,同桌3人被判赔偿近20万元
  • 美国考虑让移民上真人秀竞逐公民权,制片人称非现实版《饥饿游戏》
  • 上市公司重大资产重组新规九要点:引入私募“反向挂钩”,压缩审核流程
  • 秦洪看盘|风格有所转变,热钱回流高弹性品种
  • 全国省市县国土空间总体规划已基本批复完成,进入全面实施阶段