首页 > 解决方案 > [UWP/MVVM]RadDataGrid 数据模板列中的启用/禁用按钮,该按钮根据条件绑定了命令

问题描述

我设置了一个 bool 属性并将其绑定到 xaml 中的 IsEnabled,但是 ICommand CanExecute 方法覆盖了 xaml 中的 IsEnabled,因此我的 bool 属性无效。

当我在视图模型的 CanExecute 方法中定义条件时,它要么禁用该方法绑定到的所有按钮,要么启用所有按钮。

它是一个网格,每行显示 3 个不同的按钮,每个按钮都转到一个新的 xaml 屏幕。如果在按钮所在的行上没有特定条件的数据,则需要禁用该按钮。

我该如何进行设置,以便在某种情况下禁用按钮?

自定义命令:

public class CustomCommand : ICommand
{

    private Action<object> execute;
    private Predicate<object> canExecute;
    public CustomCommand(Action<object> execute, Predicate<object> canExecute)
    {
        this.execute = execute;
        this.canExecute = canExecute;

    }

    public event EventHandler CanExecuteChanged
    {
        add
        {

        }
        remove
        {

        }
    }

    public bool CanExecute(object parameter)
    {
        //throw new NotImplementedException();
        bool b = canExecute == null ? true : canExecute(parameter);
        return b;
    }

    public void Execute(object parameter)
    {
        execute(parameter);
    }
}

xml

<DataTemplate>
                                <Button Command="{Binding Source={StaticResource VM},
                                Path=Command}" CommandParameter="{Binding}" >
                                    <SymbolIcon Symbol="Edit" Foreground="AliceBlue" />
                                </Button>
</DataTemplate>

可以在 VM 中执行

 private bool CanGetDetails(object obj)
    {
        return true;
    }

标签: c#.netxamluwp

解决方案


我认为你可以从 MVVMLight 的 RelayCommand 中挑选很多代码。尝试将您的活动更改为

    public event EventHandler CanExecuteChanged
    {
        add
        {
            if (canExecute != null)
            {
                CommandManager.RequerySuggested += value;
            }
        }

        remove
        {
            if (canExecute != null)
            {
                CommandManager.RequerySuggested -= value;
            }
        }
    }

并添加一个功能

    public void RaiseCanExecuteChanged()
    {
        CommandManager.InvalidateRequerySuggested();
    }

然后,无论您在命令中作为谓词放置什么,在谓词的布尔设置器中执行以下操作:

SomeCustomCommand.RaiseCanExecuteChanged()

希望我有所帮助。


推荐阅读