最近刚刚换了工作,到了新公司的接到第一个项目,是做一个分店零售POS系统。客户对界面要求比较高,所以采用了WPF做为客户端开发技术。在POS系统中,快捷键是比较重要的功能,有很多快捷键在功能是实现上相似,WPF需要在每个页面上配置InputBindings。为了维护、开发便利,对 ...
最近刚刚换了工作,到了新公司的接到第一个项目,是做一个分店零售POS系统。客户对界面要求比较高,所以采用了WPF做为客户端开发技术。在POS系统中,快捷键是比较重要的功能,有很多快捷键在功能是实现上相似,WPF需要在每个页面上配置InputBindings。为了维护、开发便利,对快捷键做统一管理,变得很有必要。现在我来介绍一下实现。
要做到统一管理,我的想法就是让快捷键变成可配置的,其次,能根据配置自动绑定快捷键及处理句柄。废话不多说直接上代码。
1、KeyboardShortcuts 快捷键统一管理的入口
public class KeyboardShortcuts { private const get='_blank'>string COFINGFILE = "KeyboardShortcutsRule.Config"; public KeyboardShortcuts() { Rules = new List<KeyboardShortcutsRule>(); LoadConfig(); } public List<KeyboardShortcutsRule> Rules { get; set; } public void ActiveKeysBindings(Window window) { foreach (var item in Rules) { if (!item.IgnoreWindow.Contains(window.GetType())) { if (item.Effectivity.Count == 0 || item.Effectivity.Contains(window.GetType())) { window.InputBindings.Add(new InputBinding(item.Command.GetCommand(), new KeyGestureConverter().ConvertFromString(item.Keys) as KeyGesture) { CommandParameter = window }); } } } } private static KeyboardShortcuts current = null; public static KeyboardShortcuts Current { get { if (current == null) { current = new KeyboardShortcuts(); } return current; } } public void LoadConfig() { try { XDocument doc = XDocument.Load(COFINGFILE); this.Rules = doc.Element("Settings").Elements("KeyboardShortcuts") .Select(o => new KeyboardShortcutsRule() { Name = o.Attribute("Name").Value, IsShowInHelp = o.Attribute("IsShowInHelp") != null ? Convert.ToBoolean(o.Attribute("IsShowInHelp").Value) : true, Keys = o.Attribute("Keys").Value, IgnoreWindow = new List<Type>().InitListType(o.Elements("Ignore")), Effectivity = new List<Type>().InitListType(o.Elements("Effect")), Command = o.Attribute("Command").Value.InitCommand() } ).ToList(); } catch { } } public void SaveConfig() { try { XDocument doc = new XDocument(); var element = new XElement("Settings"); foreach (var item in Rules) { var cmdType = item.Command.GetType(); XElement node = new XElement( "KeyboardShortcuts", new XAttribute("Name", item.Name), new XAttribute("Keys", item.Keys), new XAttribute("IsShowInHelp", item.IsShowInHelp), new XAttribute("Command", string.Format("{0}|{1}", cmdType.Assembly.FullName, cmdType.ToString()))); foreach (var childItem in item.IgnoreWindow) { XElement ignoreList = new XElement("Ignore", childItem); node.Add(ignoreList); } foreach (var childItem in item.Effectivity) { XElement effectList = new XElement("Effect", childItem); node.Add(effectList); } element.Add(node); } doc.Add(element); doc.Save(COFINGFILE); } catch { } } }
原标题:WPF 快捷键统一管理
关键词:wpf
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。