C#WPF界面MVVM框架下异步命令的启动和停止及绑定

框架采用CommunityToolkit.Mvvm,界面如下

View的XAML代码

cs 复制代码
<Window x:Class="WpfApp6.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:WpfApp6"
        xmlns:FF="clr-namespace:WpfApp6"  
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="300">

    <Grid>
        <StackPanel Height="200" Background="AliceBlue" Orientation="Vertical"   Width="300" >
            <TextBlock Name="Lb" Text="{Binding myMessage.Message,Mode=OneWay}" Height="40" Background="LightCoral"/>
            <Button x:Name="btnclick" Content="Run"  Background="Gold" Command="{Binding ExecCommand }" Height="40" BorderThickness="3,2,3,2"/>
            <CheckBox Content="按钮状态" IsChecked="{Binding  ExecCommand.IsRunning,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
            <Button x:Name="btnCancelclick" Content="Stop"  Background="Gold" Command="{Binding CancleExecCommand }" Height="40" BorderThickness="3,2,3,2"/>
        </StackPanel>
    </Grid>
</Window>

ViewModel如下

cs 复制代码
// Ignore Spelling: App

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;

using System;
using System.Threading;
using System.Threading.Tasks;

namespace WpfApp6
{

    public class MainWinViewModel : ObservableRecipient, IRecipient<MyMessage>
    {
        public MainWinViewModel()
        {
            this.IsActive = true; 
            ExecCommand = new AsyncRelayCommand(ExecAsync);
            CancleExecCommand = new RelayCommand(ExecCommand.Cancel);
        }
        public void Receive(MyMessage message)
        {
            myMessage.Message = $"Num={message.Id},Str={message.Message}";
        }
        public MyMessage myMessage { get; set; }=new MyMessage() { Id =1, Message="原始信息"};
        public AsyncRelayCommand ExecCommand { get; }
        private  async Task ExecAsync( CancellationToken cancellationToken)
        {
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                    return;
                await Task.Delay(1);
                WeakReferenceMessenger.Default.Send(new MyMessage { Id = 123, Message = DateTime.Now.ToString() });
            } 
        }
        public RelayCommand CancleExecCommand { get; set; }

    }
}

Model如下:

cs 复制代码
using CommunityToolkit.Mvvm.ComponentModel;

namespace WpfApp6
{
    public partial class MyMessage : ObservableObject
    {
        [ObservableProperty]
        private int? id;
        [ObservableProperty]
        private string? message;  
    }
}

ViewModel和View的连接:

cs 复制代码
 public partial class MainWindow : Window
 {
     public MainWindow()
     {
         InitializeComponent();
         DataContext = new MainWinViewModel();//建立viewmodel和view的联系
     }
 }
相关推荐
大熊程序猿6 分钟前
《开篇:课程目录》
前端·c#
爱学习的capoo7 分钟前
matlab自控仿真【第一弹】❀传递函数和输出时域表达式
开发语言·matlab
EverBule17 分钟前
Python 训练 day46
开发语言·python
周杰伦fans26 分钟前
C#中用于控制自定义特性(Attribute)
后端·c#
蓝婷儿2 小时前
6个月Python学习计划 Day 18 - 项目实战 · 学生成绩管理系统(OOP版)
开发语言·python·学习
HINOTOR_2 小时前
DAY 25 异常处理
开发语言·python
yorushika_2 小时前
python打卡训练营打卡记录day49
开发语言·python·tensorboard·cbam
还是鼠鼠2 小时前
HTTP 请求协议简单介绍
java·开发语言·网络·网络协议·http
nuclear20112 小时前
使用 C# 将 Word、Excel、PDF 和 PPT文档转换为 Markdown 格式
c#·word转markdown·pdf转markdown·excel转markdown·ppt转markdown·doc转markdown·docx转markdown
on the way 1232 小时前
行为设计模式之Command (命令)
java·开发语言·设计模式