一、名詞解釋
Code Snippet,代碼模板,是一種快速生成代碼的快捷方式,使用它可以有效地提高編程效率。
編程中可以使用Visual Studio提供的預先設置好的Code Snippet,也可以根據需要創建自己的Code Snippet。
二、使用方法演示
使用code snippet創建屬性:
1. 輸入prop,出現下圖所示的提示:
2. 連按兩下Tab鍵,得到如下代碼:
3. 按一下Tab鍵,可以在橙色背景色的可更改字段之間來回跳轉,編輯后得到自定義的屬性:
public string FirstName { get; set; }
三、創建自己的Code Snippet
以創建具有通知功能的屬性為例,該種屬性是基於Caliburn.Micro框架的,寫在ViewModel中,可與View界面上的控件進行綁定。
-
在Visual Studio的Tools菜單里,找到Code Snippets Manager,
-
在Language下拉框中選擇Visual C#,
-
在Location下面的很多文件夾中,找到Visual C#文件夾,可以看到很多code snippet文件,根據路徑打開該文件夾,
-
將propfull.snippet文件復制出來,我們將基於它修改得到自己的code snippet,重命名為propcn.snippet,cn是Caliburn.Micro和Notification的縮寫,
-
打開propcn.snippet,開始修改,
-
修改<Header>中的代碼為:
<Title>propcn</Title> <Shortcut>propcn</Shortcut> <Description>Code snippet for Notification property in Caliburn.Micro</Description>
修改<Code>中的代碼為:
<Code Language="csharp"> <![CDATA[private $type$ $field$; public $type$ $property$ { get { return $field$;} set { $field$ = value; NotifyOfPropertyChange(() => $property$); } } $end$]]> </Code>
7. 保存propcn.snippet,並將該新的code snippet文件剪切到Visual C#文件夾下,至此就創建好了自己的code snippet,試試打開Visual Studio使用它:
輸入propcn,連按兩下Tab鍵,得到如下代碼片段,修改為自己需要的屬性即可啦。
private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; NotifyOfPropertyChange(() => FirstName); } }
四、常用的Code Snippet
ctor → 構造函數
for → for循環
prop → 簡化類型的屬性
propfull → 完整屬性
propdp → 依賴屬性
五、添加XAML code snippet
主要步驟同上,找到XAML code snippet的文件夾,將新建的代碼模板文件放入,在XAML中編程時輸入縮寫再敲擊兩下Tab鍵。
例如,2行2列的Grid模板:
<?xml version="1.0" encoding="utf-8"?> <CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <Header> <SnippetTypes> <SnippetType>Expansion</SnippetType> </SnippetTypes> <Title>2X2 Grid</Title> <Author>Microsoft Corporation</Author> <Description>XAML snippet for a 2X2 Grid</Description> <HelpUrl></HelpUrl> <Shortcut>2by2Grid</Shortcut> </Header> <Snippet> <Declarations> <Literal Editable="true"> <ID>Height1</ID> <ToolTip>Height of row 0</ToolTip> <Default>*</Default> <Function> </Function> </Literal> <Literal Editable="true"> <ID>Height2</ID> <ToolTip>Height of row 1</ToolTip> <Default>*</Default> <Function> </Function> </Literal> <Literal Editable="true"> <ID>Width1</ID> <ToolTip>Width of column 0</ToolTip> <Default>*</Default> <Function> </Function> </Literal> <Literal Editable="true"> <ID>Width2</ID> <ToolTip>Width of column 1</ToolTip> <Default>*</Default> <Function> </Function> </Literal> </Declarations> <Code Language="XAML"> <![CDATA[ <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="$Width1$"/> <ColumnDefinition Width="$Width2$"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="$Height1$"/> <RowDefinition Height="$Height2$"/> </Grid.RowDefinitions> </Grid> ]]> </Code> </Snippet> </CodeSnippet>
也可以下載一些現成的模板文件,例如CodePlex Archive 的XAML snippets:https://archive.codeplex.com/?p=xamlsnippets