我正在尝试将我自己的命令绑定(bind)到一个按钮,但我没有尝试任何工作。
我得到了窗口的 DataContext
通过 XAML 绑定(bind),但是当我尝试绑定(bind)到我的命令时,IntelliSense 没有看到它,并且该命令没有执行。我尝试通过代码隐藏进行绑定(bind),但也遇到了相同的结果。
window 的Binding
看起来像这样。
DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=Commands}"
mainViewModelLocator
传递 Commands
的新实例类(class)。Commands
类(class) :public ICommand GradeCommand { get; set; }
public Commands()
{
LoadCommands();
}
private void LoadCommands()
{
GradeCommand = new CustomCommand(GradeClick, CanGradeClick);
}
private void GradeClick(object obj)
{
MessageBox.Show("Test");
}
private bool CanGradeClick(object obj)
{
return true;
}
和
ICommand
:private Action<object> execute;
private Predicate<object> canExecute;
public CustomCommand(Action<object> execute, Predicate<object> canExecute)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
bool b = canExecute == null ? true : canExecute(parameter);
return b;
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
execute(parameter);
}
最佳答案
我想到了。我的 DataContext 绑定(bind)不起作用。
我将其更改为:
xmlns:vm="clr-namespace:ProgramName.ViewModel"
<Window.DataContext>
<vm:Commands/>
</Window.DataContext>
关于c# - 绑定(bind)命令的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816697/