我希望在我的ViewModel中接收命令(即根本沒有任何代碼)。我在視圖中設置了KeyBindings,但我不確定如何在視圖模型上構建命令,我該如何操作?我已經嘗試了下面的代碼,但它永遠不會被調用。WPF中的鍵盤快捷鍵路由到ViewModel
我收到此錯誤在輸出窗口
BindingExpression path error: 'ShowHelp' property not found on 'object' ''String' (HashCode=-1833871577)'. BindingExpression:Path=ShowHelp; DataItem='String' (HashCode=-1833871577); target element is 'KeyBinding' (HashCode=60325168); target property is 'Command' (type 'ICommand')
視圖模型被像這樣定義:(注意,這適用於窗口中的所有其他綁定)
<app:ViewModel x:Key="viewModel"></app:ViewModel>
XAML:
<Window.InputBindings>
<KeyBinding Command="{Binding ShowHelp, Source=viewModel}" Gesture="ALT+H" />
</Window.InputBindings>
視圖模型代碼
這是我已經開始與視圖模型代碼來執行命令,如果這是錯誤的請指教:)
public class ShowHelpCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Console.WriteLine("SHOW HELP");
}
}
public ICommand ShowHelp { get; set; }
ShowHelp = new ShowHelpCommand();
是的Erik,是的 - 謝謝! – Chris
在'object''String'上找不到''ShowHelp'屬性的錯誤信息在閱讀時很有幫助......;) – erikH
是啊:)我只是不知道該怎麼做才能做到這一點! – Chris