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 分钟前
基于MATLAB边缘检测博文
开发语言·算法·matlab
何曾参静谧14 分钟前
「Py」Python基础篇 之 Python都可以做哪些自动化?
开发语言·python·自动化
Prejudices17 分钟前
C++如何调用Python脚本
开发语言·c++·python
我狠狠地刷刷刷刷刷30 分钟前
中文分词模拟器
开发语言·python·算法
wyh要好好学习34 分钟前
C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中
开发语言·c#·wpf
AitTech34 分钟前
C#实现:电脑系统信息的全面获取与监控
开发语言·c#
qing_04060337 分钟前
C++——多态
开发语言·c++·多态
孙同学_37 分钟前
【C++】—掌握STL vector 类:“Vector简介:动态数组的高效应用”
开发语言·c++
froginwe1138 分钟前
XML 编辑器:功能、选择与使用技巧
开发语言
Jam-Young44 分钟前
Python的装饰器
开发语言·python