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的联系
     }
 }
相关推荐
Vacant Seat43 分钟前
图论-实现Trie(前缀树)
java·开发语言·数据结构·图论
猪猪虾的业余生活1 小时前
Qt 驾校考试系统项目实现
开发语言·qt
香菇滑稽之谈1 小时前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式
风莫寻1 小时前
【Troubleshot】Qt 长按按键 keyPressEvent keyReleaseEvent 自动重复问题
开发语言·qt
ZC·Shou1 小时前
Rust 之一 基本环境搭建、各组件工具的文档、源码、配置
开发语言·rust·cargo·rustc·rustup·clippy·rustfmt
Hello.Reader1 小时前
深入理解 Rust 中的模式匹配语法
开发语言·rust
最胖的小仙女1 小时前
通过动态获取后端数据判断输入的值打小
开发语言·前端·javascript
阿波拉1 小时前
AttributeError: module ‘backend_interagg‘ has no attribute ‘FigureCanvas’问题解决
开发语言·python
臣妾写不来啊2 小时前
使用dify的api连接外部知识库,dify连接ragflow的知识库(附java代码)
java·开发语言·spring boot
hhw1991122 小时前
C#面试题整理11
c#