[英]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.