2014-10-28 39 views
0

我有一個MainView(窗口)作爲一個shell,其中當用戶導航應用程序時,我加載包含不同「頁面」或「視圖」的不同用戶控件。在UserControl中的WPF InputBinding doesent工作,直到集中

我通過將ViewModel設置爲MainView上的Content屬性來更改視圖。 DataTemplate根據ViewModel選擇正確的視圖。

我想使用F1鍵盤快捷鍵來觸發當前UserControl上的命令。

如果我在UserControl上添加InputBindings,我必須在UserControl中選擇一些內容,然後才能點擊F1。

如果我在窗口上添加InputBindings,我沒有正確的DataContext(ViewModel)。我甚至試圖CommandTarget設置的內容屬性視圖模型

<Window.InputBindings> 
    <KeyBinding Key="F1" CommandTarget="{Binding ElementName=ContentControl}" Command="{Binding ShowInfoCommand}" /> 
</Window.InputBindings> 

我自己也嘗試設置FocusManager.FocusedElement =「{綁定的ElementName = ContentControl中}」的主窗口和調焦=在用戶控件,甚至ContentControl中真。

回答

0

我在這裏發現了一個很好的解決方案at SOAdi Lester。他正在使用行爲將用戶控件的鍵綁定傳播到窗口

我發現如果您在generic.xaml中的泛型內容模板中使用該行爲,則必須通過TemplatedParent綁定命令而不是TemplateBinding

<Border behaviors:InputBindingBehavior.PropagateInputBindingsToWindow="True"> 
    <Border.InputBindings> 
     <KeyBinding Key="F1" Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ShowInfoCommand}" /> 
    </Border.InputBindings> 
</Border>