【发布时间】:2017-08-15 11:28:07
【问题描述】:
我正在学习/练习 C# 中的基本 MVVM 框架解决方案
我有一个使用 ComboBox 的小程序,如果用户从框中选择某些内容,它会显示在 MsgBox 中。现在我希望它在 esc 键上关闭。我在这里发现了很多已解决的问题,例如:
Keyboard events in a WPF MVVM application? Press Escape key to call method
但我无法实现其中任何一个...我什至似乎无法将 KeyPreview 设置为 True(我现在可以直接写入表单,但有趣的是,我不能让它工作。)
我的问题是,我有一段时间没有使用 c#,我不确定到底该使用什么(KeyEventArg KeyEventHandler,我应该使用 e.Key,e.keyDown 吗?)而且我不知道该把这段代码放在哪里。我在 XAML 文件中阅读了一些关于如何处理它的内容,这将是最好的,但无法做到。现在这是我在 App.xaml.cs 中的代码,我尝试在各个地方实现它,但我再次询问我何时编码并且不知道该做什么/我到底在做什么,所以我在这里。
我现在的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace WpfComboBoxStrinbgListMVVM
{
public class MainViewModel
{
public MainViewModel()
{
ItemList = new List<string> { "item1", "item2", "item3" };
}
public List<string> ItemList { get; set; }
private string seletedElement;
public string SelectedElement
{
get { return seletedElement; }
set
{
seletedElement = value;
MessageBox.Show(seletedElement);
}
}
private void EscKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
MessageBox.Show("Escape key pressed");
// mainWindow.Close();? MainWievModel.Close(); App.Close();
}
}
//private void Form1_KeyDown(object sender, KeyEventArgs e)
//{
// if (e.KeyCode == Keys.Escape)
// {
// MessageBox.Show("Escape key pressed");
// // prevent child controls from handling this event as well
// e.SuppressKeyPress = true;
// }
//}
}
}
【问题讨论】:
-
我无法让按下 Esc 键的 MsgBox 出现,如果你想帮助我,请询问你需要的任何东西:)
-
“现在我希望它在 esc 键上关闭” - 什么是“它”?
-
应用程序本身,程序,整个事情(我有另一个项目,在 Esc 上登录窗口消失但仍在任务管理器中运行,我希望能够正确关闭它)