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的联系
     }
 }
相关推荐
m0_694845573 分钟前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
春日见8 分钟前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
C++ 老炮儿的技术栈11 分钟前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
心疼你的一切16 分钟前
Unity异步编程神器:Unitask库深度解析(功能+实战案例+API全指南)
深度学习·unity·c#·游戏引擎·unitask
派葛穆18 分钟前
Python-批量安装依赖
开发语言·python
MSTcheng.30 分钟前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
晓131332 分钟前
第七章 【C语言篇:文件】 文件全面解析
linux·c语言·开发语言
愚者游世32 分钟前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
梵刹古音35 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
Ekehlaft38 分钟前
这款国产 AI,让 Python 小白也能玩转编程
开发语言·人工智能·python·ai·aipy