我创建了一个按钮,其命令参数已设置,并使用实现 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 所说,部分问题可以通过交换 Command
和 CommandParameter
的 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/