Nik*_*wal 4 .net c# wpf icommand
我创建了一个按钮,其命令参数设置和命令使用实现ICommand接口的类.但是我的按钮被禁用了.这是为什么?我从这里得到了这个代码:ICommand就像一块巧克力蛋糕
<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>
Run Code Online (Sandbox Code Playgroud)
我的班级是
class HelloWorldCommand:ICommand
{
public bool CanExecute(object parameter)
{
return parameter != null;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show(parameter.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,这是非常非常简单的实现ICommand.
正如@JleruOHeP所说,部分问题可以通过交换Command和的setter来解决CommandParameter.但这很丑陋,因为你每次都要记住这个序列.
更正确的方法是告诉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());
}
}
Run Code Online (Sandbox Code Playgroud)
现在,制定者的顺序是无关紧要的.
要了解它是如何CommandManager工作的,你可以阅读Josh Smith的这篇好文章.
最简单的答案 - 切换Command和Command参数的位置:
<Button CommandParameter="Hello" Command="{StaticResource hwc}" .../>
Run Code Online (Sandbox Code Playgroud)
但是@Dennis给出了更好的一个