c# - 即使在 WPF 中提供 CommandParameter 后按钮也未启用

标签 c# .net wpf icommand

我创建了一个按钮,其命令参数已设置,并使用实现 ICommand 接口(interface)的类进行命令。但是我的按钮被禁用了。这是为什么?我从这里得到这段代码:ICommand is like a chocolate cake

<Window x:Class="ICommand_Implementation_CSharp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ICommand_Implementation_CSharp"
    Title="MainWindow" Height="350" Width="525">
<Grid>      
    <Grid>
        <Grid.Resources>
            <local:HelloWorldCommand x:Key="hwc"  />
        </Grid.Resources>

        <Button Command="{StaticResource hwc}" CommandParameter="Hello" 
                Height="23" HorizontalAlignment="Left" Margin="212,138,0,0" 
                Name="Button1" VerticalAlignment="Top" Width="75">Button</Button>
    </Grid>
</Grid>

我的类(class)是

class HelloWorldCommand:ICommand
{
    public bool CanExecute(object parameter)
    {
        return parameter != null;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        MessageBox.Show(parameter.ToString());
    }
}

最佳答案

好吧,这是 ICommand 的非常非常简单的实现。

正如@JleruOHeP 所说,部分问题可以通过交换 CommandCommandParameter 的 setter 来解决。但这是一种丑陋的方式,因为你每次都必须记住顺序。

更正确的方法是告诉 CommandManager 重新查询命令状态:

public class HelloWorldCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return parameter != null;
    }

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

    public void Execute(object parameter)
    {
        MessageBox.Show(parameter.ToString());
    }
}

现在 setter 的顺序是无关紧要的。
要了解 CommandManager 的工作原理,您可以阅读 this Josh Smith 的精彩文章。

关于c# - 即使在 WPF 中提供 CommandParameter 后按钮也未启用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104274/

相关文章:

wpf - 如何使用 token 在 MVVM light 中发送简单的字符串消息

c# - 如何用字符串索引声明字符串数组?

c# - 注释复杂类型时远程验证失败

c# - 在多个名称迭代器上移动下一个

Web 服务的 .NET 编码标准和框架

wpf - CollectionViewSource 是如何工作的?

c# - 从 DynamicResource 为 BorderBrush 设置动画会使用该画笔为所有内容设置动画

c# - 该方法或操作未实现。在 C# 中停止 IIS 网站时

c# - 使用 JsonConverterAttribute 装饰类时使用默认的 JsonSerializer

c# - 使用VS 2005设计抽象形式