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

C# WPF 命令机制(关闭CanExecute自动触发,改手动)

在绑定数据变化时手动触发UI状态检查

<Window x:Class="WpfApp5.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:WpfApp5"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="点击"  
                Command="{Binding ClickCommand}"  
                Margin="10" Padding="15" />
        <Button Content="Sub"  
        Command="{Binding ClickCommandSub}"  
        Margin="10" Padding="15" />
        <TextBlock Text="{Binding Count, StringFormat='已点击次数: {0}'}"  
                   HorizontalAlignment="Center" Width="80" Margin="10"/>
    </StackPanel>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}



public class ManualRelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public ManualRelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;
    public void Execute(object parameter) => _execute(parameter);

    // 手动触发事件  
    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

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

     同时保留手动触发方法  
    //public void ForceRaiseCanExecuteChanged() => CommandManager.InvalidateRequerySuggested();
}

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));


    private int _count;
    public int Count
    {
        get => _count;
        set
        {
            if (_count == value) return;
            _count = value;
            OnPropertyChanged();
            // 手动触发命令状态更新  
            ClickCommand.RaiseCanExecuteChanged();
        }
    }

    public ManualRelayCommand ClickCommand { get; }
    public ICommand ClickCommandSub
    {
        get { return new ManualRelayCommand(_ => Count--, _ => true); }
        set { }
    }

    public MainViewModel()
    {
        ClickCommand = new ManualRelayCommand(
            ClickEvent,
           _CanExecute 
        );
    }
    private void ClickEvent(object obj)
    {
        Count++;
    }

    private bool _CanExecute(object arg)
    {
        return Count < 3;
    }
}
http://www.dtcms.com/a/113683.html

相关文章:

  • Apifox接口测试工具详细解析
  • C# 多线程并发编程基础
  • 【Block总结】PagFM,像素注意力引导融合模块|即插即用
  • 基于STM32的智能门禁系统设计与实现
  • 05-Spring Security 认证与授权机制源码解析
  • python爬虫爬取淘宝热销(热门)零食商品加数据清洗、销量、店铺及词云数据分析_源码及相关说明文档;售后可私博主
  • 【学Rust写CAD】27 双线性插值函数(bilinear_interpolation.rs)
  • python爬虫:DrissionPage实战教程
  • 基于FAN网络的图像识别系统设计与实现
  • 【软考-高级】【信息系统项目管理师】【论文基础】范围管理过程输入输出及工具技术的使用方法
  • linux提取 Suid提权入门 Sudo提权入门
  • (二)使用Android Studio开发基于Java+xml的安卓app之环境搭建
  • 状态机思想编程练习
  • 【学习笔记】pytorch强化学习
  • flutter 专题 七十三Flutter打包未签名的ipa
  • Media streaming mental map
  • 马吕斯定律(Malus‘s Law)
  • [Hot 100] 221. 最大正方形 215. 数组中的第K个最大元素 208. 实现 Trie (前缀树) 207. 课程表
  • Nmap全脚本使用指南!NSE脚本全详细教程!Kali Linux教程!(五)
  • 7-12 最长对称子串(PTA)
  • verilog状态机思想编程流水灯
  • VMware 安装 Ubuntu 全流程实战指南:从零搭建到深度优化
  • 医药档案区块链系统
  • 强引用,弱引用,软引用,虚引用,自旋锁,读写锁
  • 基于springboot放松音乐在线播放系统(源码+lw+部署文档+讲解),源码可白嫖!
  • Linux驱动-①电容屏触摸屏②音频③CAN通信
  • client-go如何监听自定义资源
  • 2011-2019年各省地方财政资源勘探电力信息等事务支出数据
  • Jetpack Compose 自定义标题栏终极指南:从基础到高级实战
  • 蓝桥杯2024年第十五届省赛真题-宝石组合