我主要关注本教程:http://www.codeproject.com/Articles/238657/How-to-use-Commands-in-WPF
但后来我意识到RelayCommand
是我无法使用的另一个框架的一部分。这是我的代码:
public ICommand TestCommand
{
get;
internal set;
}
private bool CanExecuteTestCommand()
{
return !string.IsNullOrEmpty(txtUsername);
}
private void CreateTestCommand()
{
TestCommand = new TestCommand(TestExecute, CanExecuteTestCommand);
}
public void TestExecute(object parameter)
{
obj.TestConnection();
}
和XAML:
<Button Content="Test Connection" Command="{Binding Path=TestConCmd}" />
但这不会编译,因为TestCommand
显然是无效的类型。
我也查看了这个教程:
http://www.codeproject.com/Articles/274982/Commands-in-MVVM
但同样地,即使我已添加Command
,using System.Windows.Input
似乎也不是一种类型。
然后,我所看到的所有其他教程只使用内置命令,例如关闭应用程序,从剪贴板粘贴以及其他一些内容。
那么......我如何实际创建我的命令?
答案 0 :(得分:0)
Command
不是类型,ICommand
是。你必须从/实现它:
public class TestCommand : ICommand
{
public override void Execute(object parameter)
{
//Do stuff
}
}
随后实施这些方法,尤其是Execute(object parameter)
。然后你可以这样做:
TestCommand = new TestCommand();
像以前一样在您的视图模型中。当然,您可以重新实现RelayCommand或类似的东西。 Is Josh Smith's implementation of the RelayCommand flawed?显示一些代码,容易出错。