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

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

xml 复制代码
<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>
csharp 复制代码
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;
    }
}
相关推荐
宝桥南山4 分钟前
DeepSeek - 尝试一下GitHub Models中的DeepSeek
microsoft·ai·微软·c#·github·.net
code bean3 小时前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
lljss20207 小时前
C# 一个解决方案放一个dll项目,一个dll测试项目 ,调试dll项目的源码
c#
沉到海底去吧Go7 小时前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
lph19727 小时前
自定义事件wpf
wpf
code bean12 小时前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf
ghost14315 小时前
C#学习第27天:时间和日期的处理
开发语言·学习·c#
jason成都15 小时前
c#压缩与解压缩-SharpCompress
开发语言·c#
傻啦嘿哟16 小时前
从零开始:用Tkinter打造你的第一个Python桌面应用
开发语言·c#
CodeCraft Studio17 小时前
PDF处理控件Aspose.PDF教程:在 C# 中更改 PDF 页面大小
前端·pdf·c#