WPF UserControl响应PreviewKeyDown事件方法
生活随笔
收集整理的這篇文章主要介紹了
WPF UserControl响应PreviewKeyDown事件方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前在一個項目中,Window窗口嵌入UserControl頁面,在UserControl控件頁面中添加PreviewKeyDown或者KeyDown事件,軟件均不觸發事件;在Window窗口可以響應事件,但是由于項目上下文綁定,調用不到想要執行的函數,所以寫個文章記錄一下,以便后期遇到同樣問題,能及時解決。
1、UserControl后臺邏輯處理頁面中添加
public void CallKeyDown(KeyEventArgs e) {if (e.Key == Key.Space){if (DataContext != null){if (((MainViewModel)DataContext).MagnetronVM != null)if (((MainViewModel)DataContext).MagnetronVM.IsEnabled_Position == true)((MainViewModel)DataContext).MagnetronVM.StopCtrl(); }} }2、在Window的xaml 窗口設置中添加PreviewKeyDown事件
<Window x:Class="RealStomach_WPF.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:RealStomach_WPF"Height="950" Width="1800"PreviewKeyDown="Window_PreviewKeyDown"><Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Fill"><StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,0,5,0"><local:RealMainView x:Name="realView" Background="#FF0E121B"/></StackPanel></Viewbox> </Window>3、Window 后臺邏輯處理,響應PreviewKeyDown事件:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e) {this.realView.CallKeyDown(e); }擴展:
在Panel(StackPanel、Canvas、Grid)上或者是在一些默認不支持Focus的控件上添加了KeyDown或者KeyUp,處理方法在鼠標左鍵點擊事件中,讓控件獲取到焦點,并且設置該控件Focusable="True";
具體代碼示例:
<!--前端UI--> <StackPanel x:Name="stanpan" Focusable="True"/> //后臺左鍵響應事件 private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {Grid1.Focus(); }?
總結
以上是生活随笔為你收集整理的WPF UserControl响应PreviewKeyDown事件方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 常识(转)
- 下一篇: .NetCore生成海报+二维码(log