先介绍一下快捷键的绑定方式:
window窗口:
<Window.InputBindings>
<KeyBinding Key="F1" Command="{Binding Path=CommandKey}" />
</Window.InputBindings>
UserControl用户控件:
<UserControl.InputBindings>
<KeyBinding Key="PageUp" Command="{Binding CommandKey}" />
</UserControl.InputBindings>
快捷键绑定在主窗体Window页面或UserControl页面都可以实现,但进行二级弹框时,若是Window页面,则还起作用,若是UserControl完全没反应。 这是因为UserControl不会主动获得焦点而导致的,弹出UserControl窗体也是用Window进行弹出的,此时相当于焦点在外层Window上,而不是UserControl上面,所以以下提供3中解决方案:
1.用户控件显示的时候把焦点强制获取到(最省事的办法)
1)UserControl页面的cs类中:
public MainWindow()
{
InitializeComponent();
Focusable = true; //可接受焦点,必须先设这个属性
Focus(); //尝试获得焦点
}
2)或者再弹框的时候,进行设置
public DelegateCommand CommandShowDialog { get; set; }
KeyUserControl keyUser = null;
private void OnCommandShowDialog()
{
Window win = new Window();
keyUser = new KeyUserControl();
win.Content = keyUser;
keyUser.Focusable = true;
keyUser.Focus();
win.Show();
}
2.用MouseEnter事件(友情提示:给窗体加上背景色,不然不起作用)
1)在usercontrol页面对应的cs类中设置:
public KeyUserControl()
{
InitializeComponent();
this.DataContext = new ViewModel();
MouseEnter += KeyUserControl_MouseEnter;
}
private void KeyUserControl_MouseEnter(object sender, MouseEventArgs e)
{
//方法一
var content = Content as UIElement;
if (content != null)
{
content.Focusable = true;
content.Focus();
}
//方法二,方法一可以注释掉,用方法二两行代码,道理是一样的,都是为了获取usercontrol页面的焦点
//Focusable = true;
//Focus();
}
2)也可在ViewModel中设置:
public DelegateCommand CommandShowDialog { get; set; }
KeyUserControl keyUser = null;
private void OnCommandShowDialog()
{
Window win = new Window();
keyUser = new KeyUserControl();
win.MouseEnter += KeyUserControl_MouseEnter;
win.Content = keyUser;
keyUser.Focusable = true;
keyUser.Focus();
win.ShowDialog();
}
private void KeyUserControl_MouseEnter(object sender, MouseEventArgs e)
{
keyUser.Focusable = true;
keyUser.Focus();
}
3.用KeyDown事件
不能在usercontrol页面对应的cs类中设置KeyDown事件,因为UserControl是被Window弹出的,所以此时焦点在外层Window上,UserControl没焦点,而KeyDown事件的前提是有焦点。具体原因可以看我的另一篇《WPF经典教程--键盘输入事件, 鼠标输入事件, 焦点处理》。
只能在ViewModel中设置KeyDown事件:
public DelegateCommand CommandShowDialog { get; set; }
KeyUserControl keyUser = null;
private void OnCommandShowDialog()
{
Window win = new Window();
keyUser = new KeyUserControl();
win.KeyDown += UserControl_KeyDown;
win.Content = keyUser;
keyUser.Focusable = true;
keyUser.Focus();
win.ShowDialog();
}
private void UserControl_KeyDown(object sender, KeyEventArgs e)
{
keyUser.Focusable = true;
keyUser.Focus();
}