第530篇--MVVM Code Generator
在用Prism框架开发WPF/Silverlight程序的时候,经常会要手写View对应的ViewModel代码,但是很多情况下,ViewModel的代码结构相差不会很大,一般是有Property, Constructor, Command以及一些事件,所以为了提高开发效率,本文和大家探讨用一个小工具实现ViewModel的快速开发。
基本思路
主要流程就是解析XAML代码,首先把所有有Binding的语句段抽出来。
方法:GetAllCommandPropertiesNames
/// <summary> /// 获取所有Command名字 Command="{Binding OpenFileCommand}" 或是Command="{Binding Path=SaveFileCommand}" /// </summary> /// <param name="xaml"></param> /// <returns></returns> private static List<string> GetAllCommandPropertiesNames(string xaml) { List<string> commandPropertiesNames = new List<string>(); foreach (int position in StringHelper.GetPositions(xaml, PropertyConst)) { int endPosition = StringHelper.GetNearestPositionOnStart(xaml, position + PropertyConst.Length, CloseChar); // 得到有可能的字符串如:Path=**Command 或是Path =***Command, 去除= 空格 Path // 过滤掉这种Binding情况: // CommandParameter="{Binding Path=., RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}" string result = xaml.Substring(position + PropertyConst.Length, endPosition - position - PropertyConst.Length).Replace(" ", string.Empty).Replace(PathConst, string.Empty).Replace("=", string.Empty); if (!result.Contains(RelativeBindingPath)) { commandPropertiesNames.Add(result); } } return commandPropertiesNames.Distinct().ToList(); }
抽出所有的bound属性:GetAllBindingPropertiesNames
/// <summary> /// 获取所有属性名字 Text="{Binding Age}", Text="{Binding Path=Name}" /// </summary> /// <param name="xaml"></param> /// <returns></returns> private static List<string> GetAllBindingPropertiesNames(string xaml) { List<string> bindingProperties = GetAllCommandPropertiesNames(xaml); if (bindingProperties != null && bindingProperties.Count > 0) { return bindingProperties.Where(com => com.IndexOf("Command") < 0).ToList(); } return null; }
抽取所有的bound Command: GetAllCommandNames
/// <summary> /// 获取所有Command名字 Command="{Binding OpenFileCommand}" 或是Command="{Binding Path=SaveFileCommand}" /// </summary> /// <param name="xaml"></param> /// <returns></returns> private static List<string> GetAllCommandNames(string xaml) { List<string> commands=GetAllCommandPropertiesNames(xaml); if (commands != null && commands.Count>0) { return commands.Where(com => com.IndexOf("Command") > 0).ToList(); } return null; }
Demo代码下载:https://skydrive.live.com/#cid=6B286CBEF1610557&id=6B286CBEF1610557!692
转载于:https://www.cnblogs.com/shanghaijimzhou/archive/2013/04/05/3000599.html