[英]WPF XAML Grid- KeyBinding doesn't seem to work
我正在尝试添加功能,以允许用户使用键盘“放大”在WPF应用程序的GUI上的ChromiumWebBrowser
显示的网页上。
我的XAML的代码背后有以下功能:
private void zoomInExecuted(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("'zoomInExecuted() called. ");
browser.ZoomLevel++;
}
为了使该函数能够被调用,我向用于显示ChromiumWebBrowser
的<Grid>
添加了以下<Grid.InputBindings>
标记:
<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
:
<KeyBinding Key="Add" Command="{Binding ZoomInCommand}"></KeyBinding>
public ICommand ZoomInCommand
{
get
{
_zoomIn = new DelegateCommand(CallZoomIn());
return zoomIn;
}
}
DelegateCommand是Microsoft.Practices.Prism的一部分。 您可以在这里下载
大多数MVVM框架也包括它。
缺少Icommand到方法链接部分。 其他都是正确的。 要执行方法,您需要具有ICommand类型的属性。 然后使用该属性调用所需的方法。 请查看链接。 创建了中继命令,可以将其用作通用命令,在其中可以传递要执行的方法
您无法绑定功能。 您需要创建一个ICommand来进行绑定。
假设您已在整个应用程序中实现了MVVM模式, 则需要实现RelayCommand 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.