【发布时间】:2016-06-08 11:14:52
【问题描述】:
我正在尝试添加功能,以允许用户使用键盘“放大”在我的 WPF 应用程序的 GUI 上的 ChromiumWebBrowser 中显示的网页。
我的 XAML 代码隐藏中有以下函数:
private void zoomInExecuted(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("'zoomInExecuted() called. ");
browser.ZoomLevel++;
}
为了调用这个函数,我在<Grid> 中添加了以下<Grid.InputBindings> 标签,用于显示ChromiumWebBrowser:
<Grid x:Name="grdBrowserHost" MinHeight="900" Height="Auto" MinWidth="1205" Width="Auto" Margin="5,0,0,0" DockPanel.Dock="Bottom" Grid.ColumnSpan="1" >
<Grid.InputBindings>
<KeyBinding Key="Add" Command="{Binding Path=zoomInExecuted}"></KeyBinding>
</Grid.InputBindings>
...
</Grid>
据我了解,这应该意味着当显示浏览器的网格具有焦点时,当按下键盘上的+ 按钮时,应该调用zoomInExecuted(...) 函数。
但是,当我运行我的应用程序并在浏览器中单击以确保它具有焦点时,如果我然后按键盘上的“+”,则什么也没有发生,而且我什至看不到来自我的 zoomInExecuted() 的调试控制台中的函数,所以似乎按下“+”键实际上并没有调用该函数。我是否正确完成了KeyBinding?我的代码中有什么遗漏吗?
编辑
我尝试过使用ICommand,正如答案中所建议的那样:
public ICommand zoomInCommand
{
get
{
_zoomIn = new DelegateCommand(zoomInExecuted()); //CallZoomIn());
return zoomIn;
}
}
并在 XAML 中的 KeyBinding 中调用它:
<KeyBinding Key="Add" Command="{Binding Path=zoomInCommand}"></KeyBinding>
但是我在 C# 中遇到了一个编译错误,上面写着:
找不到类型或命名空间名称“DelegateCommand”(您是否缺少 using 指令或程序集引用?)
我需要添加特定的引用或using 语句才能使用它吗?
编辑
我还尝试将<KeyBinding ...> 标签添加到保存浏览器对象的<Grid> 和XAML 中的浏览器本身,即
<Grid x:Name="grdBrowserHost" MinHeight="900" Height="Auto" MinWidth="1205" Width="Auto" Margin="5,0,0,0" DockPanel.Dock="Bottom" Grid.ColumnSpan="1" >
<Grid.InputBindings>
<KeyBinding Modifiers="Ctrl" Key="Add" Command="{Binding zoomInExecuted}"></KeyBinding>
</Grid.InputBindings>
...
<cefSharp:ChromiumWebBrowser Name="browser" Height="Auto" Width="Auto" Grid.Row="0" Address="https://web.riviam.com" Margin="25,35,-0.2,0" >
<cefSharp:ChromiumWebBrowser.InputBindings>
<KeyBinding Modifiers="Ctrl" Key="Add" Command="{Binding zoomInExecuted}"></KeyBinding>
</cefSharp:ChromiumWebBrowser.InputBindings>
</cefSharp:ChromiumWebBrowser>
但zoomInExecuted(...) 函数似乎从未被调用(我从未在控制台中看到此函数的调试)- 似乎应用程序从未注册过在键盘上按下CTRL+...
我需要将EventHandler/KeyboardListener 或类似的东西添加到应用程序中吗?
【问题讨论】:
-
Command="{Binding Path=zoomInExecuted}"表示将 Command 属性绑定到zoomInExecuted类型的ICommand属性,而不是您尝试执行的方法。阅读命令绑定。 -
您需要附加到事件并执行它的代码,构建为 ICommand,在此处查看答案:stackoverflow.com/questions/939388/binding-commands-to-events
-
DelegateCommand 是 prism MVVM 实现中的类之一。我不知道是否还有其他人,但我一直在使用 Microsoft 的 Prism 来实现 MVVM。您将哪个工具用于 MVVM。您可以在此处尝试使用 nuget 包管理器提供的 prism:nuget.org/packages/Prism.Wpf
标签: c# wpf xaml keyboard-shortcuts