这可能是世界上最容易做到的事情,但我有点挣扎。
我在XAML中有这个:
<Button Name="browseButton" Content="Browse" Grid.Column="1" />
我已经从视图到视图模型正确绑定了所有内容,如单选按钮和输入文本框等...但我想要的是将此按钮绑定到一个函数,这样当用户单击它时某些操作发生。
但是我真的很难弄清楚如何将此按钮绑定到viewmodel中的函数。我和ICommand玩过一段时间并没有走得太远,而且我不想做那些只是把它粘在后面的代码中的黑客行为。
如果有帮助,我正在使用MVVMLight(Galasoft)。
任何指导意见。
按照我https://msdn.microsoft.com/en-us/magazine/dn237302.aspx的示例,canExecuteMyCommand
在哪里进入?我如何在XAML中绑定它?
public RelayCommand BrowseCommand
{
get;
private set;
}
public LoadFilesViewModel()
{
BrowseCommand = new RelayCommand(executeBrowse, () => _canExecuteMyCommand);
}
private void executeBrowse()
{
// Do something
}
<Button Name="browseButton" Content="Browse" Grid.Column="1" Command="{Binding BrowseCommand}" />
和
public RelayCommand BrowseCommand
{
get;
private set;
}
public LoadFilesViewModel()
{
BrowseCommand = new RelayCommand(executeBrowse, () => true);
}
private void executeBrowse()
{
// Do something
}
答案 0 :(得分:2)
如果查看您提供的代码,RelayCommand
构造函数会附带2个参数。
public RelayCommand BrowseCommand
{
get;
private set;
}
public LoadFilesViewModel()
{
BrowseCommand = new RelayCommand(executeBrowse, () => _canExecuteMyCommand);
}
private void executeBrowse()
{
// Do something
}
检查source code(学习代码库和开源使这成为可能)或Visual Studio IntelliSense,您将看到此签名:
public RelayCommand(Action execute, Func<bool> canExecute)
所以第一个参数是要执行的动作,第二个参数是检查它是否可以执行。您已正确识别executeBrowse
作为&#34;做某事&#34;的方法。 _canExecuteMyCommand
参数是bool
类型的类变量,可以是true或false(在其他地方设置)。
在您自己的解决方案(已发布的问题)中,您将其替换为true(硬编码)。请注意,在这种情况下您也可以删除第二个参数:
public LoadFilesViewModel()
{
BrowseCommand = new RelayCommand(executeBrowse); // will always execute
}
<强>加成强>
请注意,您也可以使用方法来定义方法是否可以执行(或者使用委托语法内联检查逻辑),而不是使用局部变量。
public LoadFilesViewModel()
{
BrowseCommand = new RelayCommand(ExecuteBrowse, CanExecuteBrowse);
}
private void ExecuteBrowse()
{
// Do something
}
private bool CanExecuteBrowse()
{
// Check if we are allowed to browser
return true; // or false :)
}