c# - 使用 Linq 过滤 System.Windows.Forms.Keys 的可能值

标签 c# wpf linq keyboard-shortcuts

我正在使用 WPF 创建一个选项对话框,其中列出了可能的键,以便用户可以分配程序的热键。我正在尝试将 System.Windows.Forms.Keys 枚举的所有可能值过滤到仅 A-Z 和 F1-F12,然后将该列表绑定(bind)到 ComboBox。

到目前为止,这是我的代码:

Regex filter = new Regex("(^[A-Z]$)|(^F[0-9]{1,2}$)");
IEnumerable<Key> keyList = from x in (IEnumerable<Key>)Enum.GetValues(typeof(Keys)) 
                           where filter.Match(x.ToString()).Success
                           select x;
keys.DataContext = keyList;

执行此操作后,keyList 包含字母“A”两次,并且缺少字母“P”到“U”。我不知道为什么。

如果有更好的方法,我也对替代方法感兴趣。

最佳答案

您有两个拼写错误 - 您使用的是 System.Windows.Input.Key而不是 System.Windows.Forms.Keys两次。多么不幸的错别字!我建议除非你真的需要在同一个文件中同时使用 WinForms 和 WPF 的指令,否则你应该避免同时使用它们。

这是一个简短但完整的有效示例(基于您的代码,但拼写错误已修复):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

class Test
{
    static void Main()        
    {
        Regex filter = new Regex("(^[A-Z]$)|(^F[0-9]{1,2}$)");
        IEnumerable<Keys> keyList = 
            from x in (IEnumerable<Keys>) Enum.GetValues(typeof(Keys)) 
            where filter.Match(x.ToString()).Success
            select x;


        foreach (var key in keyList)
        {
            Console.WriteLine(key);
        }
    }
}

请注意,您可以使用显式类型的范围变量更轻松地编写查询表达式:
IEnumerable<Keys> keyList = from Keys x in Enum.GetValues(typeof(Keys)) 
                            where filter.Match(x.ToString()).Success
                            select x;

或使用点符号开始:
var keyList = Enum.GetValues(typeof(Keys))
                  .Cast<Keys>()
                  .Where(x => filter.Match(x.ToString()).Success);

或者,您可以使用 Unconstrained Melody并获得一个强类型列表开始:
var keyList = Enums.GetValues<Keys>()
                   .Where(x => filter.Match(x.ToString()).Success);

关于c# - 使用 Linq 过滤 System.Windows.Forms.Keys 的可能值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1585786/

相关文章:

c# - 检查 MVC 模型返回字段中的空值

c# - 动态添加行到 HTML 表

c# - WPF MVVM 我可以从 View 中使用模型吗

c# - 使用主题时的数据模板不起作用 - WPF

C# WPF 应用程序 : What is "this"?

c# - 具有多个日期字段的项目的订单集合

c# - Linq 错误 输入字符串的格式不正确。 System.Exception {System.FormatException}

c# - 自不可空引用以来的事件指南

c# - 通缉 : List of data following certain rules concerning dates

c# - 无法使用 Lambda 表达式检索值