Visual Studio自訂模板(二)

來源:互聯網
上載者:User

繼續Visual Studio自訂模板(一)的自訂模板的話題,我們進行定義更完美的模板。首先我們來分析一個Visual Studio模板檔案的構成。Visual Studio 2005匯出的模板的位置是在“[我的文件]\Visual Studio 2005\My Exported Templates\”檔案夾中,而對於項目範本,要想應用到“添加新項”的對話方塊中,必須把模板copy到“[我的文件]\Visual Studio 2005\Templates\ItemTemplates”

我們可以看到一個模板檔案就是一個zip檔案,解壓該檔案,我們會看到三個檔案,.ico, .cs, .vstemplate,ico是顯示在“添加新項”對話方塊中顯示的表徵圖,.cs檔案就是我們定義的模板原檔案,而vstemplate檔案,是一個xml檔案,該檔案定義了模板的中繼資料,對於Visual Studio 2005,該檔案的schema檔案儲存在“[Visual Studio InstallDirectory]\Xml\Schemas\2052\vstemplate.xsd”中,下面是該檔案的一個原型,

<VSTemplate Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
<TemplateData>
<DefaultName>MyClassTemplate.cs</DefaultName>
<Name>MyClassTemplate</Name>
<Description>&lt;沒有可用的說明&gt;</Description>
<ProjectType>CSharp</ProjectType>
<SortOrder>10</SortOrder>
<Icon>__TemplateIcon.ico</Icon>
</TemplateData>
<TemplateContent>
<References />
<ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">MyClassTemplate1.cs</ProjectItem>
</TemplateContent>
</VSTemplate>

至於各個結點的說明,大家可以參考上面提到的schema檔案,或者msdn(ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/dv_vsxmlref/html/6f74a2d5-3811-43d6-8b10-eb5823ad8995.htm),在<TemplateContent>結點下有一個子結點<CustomParameters>,在該結點下,我們可以方便的定義自己的模板參數,如下,

<TemplateContent>
...
<CustomParameters>
<CustomParameter Name="$MyParameter1$" Value="MyValue1"/>
</CustomParameters>
...
</TemplateContent>

上面我們定義了一個參數$MyParameter1$,該參數的值為MyValue1,自訂的模板參數跟VS提供的預設範本參數的使用方法一樣,我們可以直接在模板原檔案中使用,如下所示: 

#region Copyright (C) Rainsoft All rights reserved
/*******************************************************************************************
* Creation:
* Author: $username$
* Date: $time$
* Description: $MyParameter1$
* Version:
* Modification:
* Author:
* Date:
* Description:
* Version:
*******************************************************************************************/
#endregion

namespace $rootnamespace$
{
using System;

public class $itemname$
{
}
}

我們在Description中使用了我們剛才定義的模板參數$MyParameter1$,VS在根據該模板產生新項時,會自動的把我們定義的模板參數定義成相應的值,但這個值只能是靜態值,不能動態產生,比如在很多公司中登入windows的使用者名稱可能是公司的內部員工編號,不適合作檔案頭定義中的Author項,通過定義模板參數,我們就可以解決這個問題,但對於自訂格式的Date項,這種方式還不行,下一篇文章我將提供最終的解決方案。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.