建立 LightSwitch 螢幕範本

LightSwitch包含可用來建立具有通用型態的檢測的範本。 您也可以開發與特定資料來源,或任何資料型別,您可以使用的範本。

資料和畫面中,以指定的程式開發人員的資訊為基礎的控制項,會產生檢測範本加入螢幕對話方塊。 也可以加入程式碼,以顯示在螢幕設計檢測範本。

注意事項注意事項

這份文件示範各種檢測範本] 中可達到的案例,但不會顯示如何產生實際的範本可重複使用。當您建立範本時,您可以使用這些案例中為最佳作法。

定義檢測範本

若要建立檢測範本,首先建立一個使用 LightSwitch 延伸程式庫專案 」 範本,它由LightSwitch的可擴充性套件Microsoft Visual Studio 2012。 當您建立專案時,選取其中一個Visual Basic或 C# 的開發語言。

若要定義檢測範本

  1. 方案總管] 中,請選取 程式庫名稱。Lspkg 專案,其中 程式庫名稱是您擴充程式專案的名稱。

  2. 在功能表列上,選擇 [ 專案加入新項目

  3. 加入新項目 對話方塊中,選取 LightSwitch 檢測範本

  4. 名稱方塊中,輸入 [畫面] 範本的名稱。 這是開發人員在中看到的名稱加入螢幕對話方塊。

  5. 選擇確定 ] 按鈕。

    表示 [畫面] 範本的類別加入至 ScreenTemplates 資料夾中的設計專案。 範本名稱.vb 或 範本名稱.cs 檔案包含所有的程式碼範本。 這份文件中的範例都在該檔案中。

    兩個映像檔案也會加入至專案中,在 Resources\ScreenTemplateImages 資料夾。 這些代表中的範本則會顯示影像加入螢幕對話方塊。

Hh304432.collapse_all(zh-tw,VS.110).gif指定的顯示名稱及描述

DisplayName和Description屬性提供的名稱和描述中的 [畫面] 範本上顯示的加入螢幕對話方塊。

下列範例所示Description和DisplayName專為名稱為"測試範本 ;"檢測範本內容 您應該變更這些檔案來的有意義的名稱和描述。

Public ReadOnly Property Description As String Implements IScreenTemplateMetadata.Description
            Get
                Return "Test Template Description"
            End Get
        End Property

        Public ReadOnly Property DisplayName As String Implements IScreenTemplateMetadata.DisplayName
            Get
                Return "Test Template"
            End Get
        End Property
public string Description
        {
            get { return "TestTemplate Description"; }
        }

        public string DisplayName
        {
            get { return "Test Template"; }
        }

Hh304432.collapse_all(zh-tw,VS.110).gif指定根的資料來源

RootDataSource屬性決定了資料型別可能會顯示 [畫面] 範本。 資料型別將會出現在畫面資料 選項在 加入螢幕對話方塊。 RootDataSource屬性有四個有效的值:

Collection

能讓您選擇集合或多個結果的查詢。

ScalarEntity

能讓您選擇一個實體型別或傳回一個項目查詢。

NewEntity

用來進行檢測,要啟用 [建立新的實體。

None

用於沒有資料則要選取的畫面。

下列範例所示Collection指定成RootDataSource

Public ReadOnly Property RootDataSource As RootDataSourceType Implements IScreenTemplateMetadata.RootDataSource
            Get
                Return RootDataSourceType.Collection
            End Get
        End Property
public RootDataSourceType RootDataSource
        {
            get { return RootDataSourceType.Collection; }
        }

Hh304432.collapse_all(zh-tw,VS.110).gif判斷子集合的支援

在某些情況下,可能必須檢測範本顯示資料,以顯示在螢幕的根資料關聯的成員。 比方說,也可能繼續顯示訂單檢測範本来顯示相關訂單產品線。 若要啟用這項功能,將SupportsChildCollections屬性。 如果設定為 [ True,任何與相關集合為根資料型別將會顯示在新增畫面 ,讓開發人員可以決定是否要在一個畫面中包含這些對話方塊。

下列範例所示SupportsChildCollections屬性設定為 [ True。 若要停用子集合應該變更此選項可False:

Public ReadOnly Property SupportsChildCollections As Boolean Implements IScreenTemplateMetadata.SupportsChildCollections
            Get
                Return True
            End Get
        End Property
public bool SupportsChildCollections
        {
            get { return true; }
        }

產生螢幕內容的樹狀結構

一般而言,大多數的程式碼的檢測範本是在Generate方法。 這個方法可用來將資料檔、 程式碼或控制項加入至範本為基礎的畫面。 LightSwitch提供基本的螢幕項目,例如螢幕] 指令。 您可以修改內容項目階層架構,並建立項目,例如使用可用的儲存體模型類別ContentItem和所有相關的類別。

LightSwitch提供參考至螢幕範本產生器主機,提供產生程式碼時,它會建立一個畫面,可以使用的功能。 這個功能的一部份才提供使用主應用程式。 如果您不確定您應該建立何種結構,我們建議您建立在畫面範例LightSwitch ,然後在檢查.lsml 檔案在專案的常見資料夾,看看如何LightSwitch產生它。

Hh304432.collapse_all(zh-tw,VS.110).gif新增內容的項目] 畫面的根資料

內容項目都代表LightSwitch在螢幕上的控制項。 下列程式碼在Generate方法會顯示如何將某個內容項目至根目錄的螢幕畫面的主要資料成員。 這可能是集合或單一實體,檢測範本的類型而定。

Dim primaryDataControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, host.MakeUniqueLegalNameForContentItem("My Root Data"), host.PrimaryDataSourceProperty)
ContentItem primaryDataControl = host.AddContentItem(host.ScreenLayoutContentItem, host.MakeUniqueLegalNameForContentItem("My Root Data"), host.PrimaryDataSourceProperty);

Hh304432.collapse_all(zh-tw,VS.110).gif指定特定的控制項,使用於某個內容項目

LightSwitch控制項由ViewID,這是結合控制項的名稱和它定義所在模組的名稱。 For a list of LightSwitchViewIDs, see LightSwitch 控制項 ViewID.

下列程式碼示範如何以指定的控制項型別ContentItem與DataGrid。

host.SetContentItemView(primaryDataControl, "Microsoft.LightSwitch:DataGrid")
host.SetContentItemView(primaryDataControl, "Microsoft.LightSwitch:DataGrid");

LightSwitch使用智慧要用於特定的內容項目和它的預設屬性值的項目例如控制項的預設值。 智慧型的預設值也請考慮一個控制項,其所處內容樹狀結構中,有哪些控制項是它的父代中的資料型別等等。 如果您設定某個內容項目至特定控制項時, LightSwitch會優先處理該選項,不必使用預設值 (除非它不是有效的)。 某個特定欄位的資料型別可能您了解執行任何動作,為自訂型別,並擁有您一無所知,為控制項的預設對應。 此外,開發人員可以覆寫預設的某些情況下會選取的控制項。 因此,我們建議您設定特定的控制項內容的項目,如果您想要在所有情況下使用該特定的控制項。

Hh304432.collapse_all(zh-tw,VS.110).gif展開內容項目子的系

經常是必要展開方式為將其繫結的實體的子系的所有欄位的內容項目。 我們建議您呼叫host.ExpandContentItem來完成這項作業,而不是以手動方式做事。 這個呼叫一致且正確的方式,自動產生該控制項的預設子項目。 在下列範例中, ExpandContentItem新增預設子系 ( DataGridRow) 至DataGrid。 它也會加入至預設子系DataGridRow。 這類似於使用重設在LightSwitch螢幕設計工具。

host.ExpandContentItem(primaryDataControl)
host.ExpandContentItem(primaryDataControl);

Hh304432.collapse_all(zh-tw,VS.110).gif為非預設值的控制項上設定屬性

LightSwitch為控制項支援繼承模式。 屬性可定義在繼承階層架構中的不同層級。 比方說,所有LightSwitch控制項繼承自Microsoft.LightSwitch:RootControl,它具有通用的屬性 (水平及垂直對齊方式、 高度和寬度,等等) 調整大小的控制項。 若要在控制項上設定屬性,您必須知道哪些屬性定義的控制項型別。 為一系列內建LightSwitch控制屬性,請參閱定義、覆寫和使用 LightSwitch 控制項屬性

以下範例將設定VerticalAlignment和HeightSizingMode螢幕控制項的屬性。

host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "HeightSizingMode", "Auto")
host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "HeightSizingMode", "Auto");

我們建議您設定屬性的值,只有在需要您就必須使用這些特定值,因為如此一來會持續LightSwitch無法判斷預設的屬性值依其在螢幕的內容樹狀結構中的內容。

Hh304432.collapse_all(zh-tw,VS.110).gif設定內容的項目或螢幕成員的顯示名稱

下列範例會設定內容的項目的顯示名稱。 此範例也可以用於設定螢幕成員的顯示名稱。

host.SetDisplayName(primaryDataControl, "Main Screen Data")
host.SetDisplayName(primaryDataControl, "Main Screen Data");

如果沒有顯示名稱] 設定, LightSwitch提供預設的顯示名稱,根據內容的項目已繫結至資料。

Hh304432.collapse_all(zh-tw,VS.110).gif在螢幕的資料成員上設定屬性

以下範例將設定DisablePaging在螢幕的資料成員的屬性。 ScreenCollectionProperty代表集合螢幕成員 ; ScreenProperty代表純量型別 (實體或簡單資料型別)。

DirectCast(host.PrimaryDataSourceProperty, ScreenCollectionProperty).DisablePaging = True
((ScreenCollectionProperty)host.PrimaryDataSourceProperty).DisablePaging = true;

Hh304432.collapse_all(zh-tw,VS.110).gif將螢幕成員加入

下列範例會將字串屬性至畫面。

' Add a screen member.
            Dim screenProperty As ScreenProperty = host.AddScreenProperty("Microsoft.LightSwitch:String", "NewScreenProperty")
// Add a screen member.
            ScreenProperty screenProperty = host.AddScreenProperty("Microsoft.LightSwitch:String", "NewScreenProperty") as ScreenProperty;

Hh304432.collapse_all(zh-tw,VS.110).gif顯示選取的項目集合中的

下列範例會新增螢幕集合的選取的項目至畫面。

' Get the data type of your property.
            Dim collectionProperty As ScreenCollectionProperty = DirectCast(host.PrimaryDataSourceProperty, ScreenCollectionProperty)
            Dim collectionDataType As IEntityType = host.FindGlobalModelItem(Of ISequenceType)(collectionProperty.PropertyType).ElementType

            ' Create an expression that represents accessing the selected item on your collection property.
            Dim chain As ChainExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id))
            host.AppendMemberExpression(chain, "SelectedItem")

            ' Add a content item representing the selected item and set its view to a RowsLayout.
            Dim detailControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "ItemDetail", ContentItemKind.Details, chain, collectionDataType)
            host.SetContentItemView(detailControl, "Microsoft.LightSwitch:RowsLayout")
            host.SetControlPropertyValue(detailControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            host.ExpandContentItem(detailControl)
// Get the data type of your property.
            ScreenCollectionProperty collectionProperty = (ScreenCollectionProperty)(host.PrimaryDataSourceProperty);
            IEntityType collectionDataType = host.FindGlobalModelItem<ISequenceType>(collectionProperty.PropertyType).ElementType as IEntityType; 
// Create an expression that represents accessing the selected item on your collection property.
            ChainExpression chain = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id));
            host.AppendMemberExpression(chain, "SelectedItem");

            // Add a content item representing the selected item and set its view to a RowsLayout.
            ContentItem detailControl = host.AddContentItem(host.ScreenLayoutContentItem, "ItemDetail", ContentItemKind.Details, chain, collectionDataType);
            host.SetContentItemView(detailControl, "Microsoft.LightSwitch:RowsLayout");
            host.SetControlPropertyValue(detailControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            host.ExpandContentItem(detailControl);

Hh304432.collapse_all(zh-tw,VS.110).gif新增的群組控制項

下列範例會新增群組控制項畫面。

'Add a tabs group to the screen.
            Dim tabsGroup As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "TabsGroup", ContentItemKind.Group)
            host.SetContentItemView(tabsGroup, "Microsoft.LightSwitch:TabsLayout")
// Add a tabs group to the screen.
            ContentItem tabsGroup = host.AddContentItem(host.ScreenLayoutContentItem, "TabsGroup", ContentItemKind.Group);
            host.SetContentItemView(tabsGroup, "Microsoft.LightSwitch:TabsLayout");

Hh304432.collapse_all(zh-tw,VS.110).gif存取相關集合

可能在螢幕加入額外的相關的集合,如果開發人員指定它。 比方說,開發人員可能要顯示訂單時,包含 OrderLines。 下列範例會示範如何為螢幕添相關的集合。 請注意這段程式碼需要已在前一個範例中,「 新增群組控制 」 顯示的程式碼。

For Each p As ScreenCollectionProperty In host.ChildCollectionProperties
                'Display each child collection as a grid.
                Dim currentTab As ContentItem = host.AddContentItem(tabsGroup, host.MakeUniqueLegalNameForContentItem("Tab"), p)
                host.SetContentItemView(currentTab, "Microsoft.LightSwitch:DataGrid")
                host.ExpandContentItem(currentTab)
            Next
foreach (ScreenCollectionProperty p in host.ChildCollectionProperties)
            {
                // Display each child collection as a grid.
                ContentItem currentTab = host.AddContentItem(tabsGroup, host.MakeUniqueLegalNameForContentItem("Tab"), p);
                host.SetContentItemView(currentTab, "Microsoft.LightSwitch:DataGrid");
                host.ExpandContentItem(currentTab);
            }

Hh304432.collapse_all(zh-tw,VS.110).gif新增查詢參數

如果選取 [以顯示在螢幕的主要資料是一個查詢,其中可能包含參數。 下列範例會示範如何將參數加入至畫面。

'Add parameters to the screen.
            Dim parameterGroup As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "ParameterGroup", ContentItemKind.Group)
            host.SetContentItemView(parameterGroup, "Microsoft.LightSwitch:ColumnsLayout")
            host.SetControlPropertyValue(parameterGroup, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            For Each param As ScreenPropertyBase In host.PrimaryDataSourceParameterProperties
                host.AddContentItem(parameterGroup, param.Name, param)
            Next
// Add parameters to the screen.
            ContentItem parameterGroup = host.AddContentItem(host.ScreenLayoutContentItem, "ParameterGroup", ContentItemKind.Group);
            host.SetContentItemView(parameterGroup, "Microsoft.LightSwitch:ColumnsLayout");
            host.SetControlPropertyValue(parameterGroup, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            foreach (ScreenPropertyBase param in host.PrimaryDataSourceParameterProperties)
            {
                host.AddContentItem(parameterGroup, param.Name, param);
            }

Hh304432.collapse_all(zh-tw,VS.110).gif從實體中加入一個欄位

您可能要找出並為螢幕添傳出實體的特定欄位。 下列範例說明如何尋找實體的定義,並從 [選取的項目中加入特定欄位。 請注意第一個程式碼區塊中複製程式碼在較早的範例中,"顯示集合中的選取項目。

'Find field called "Name"
            Dim nameProperty As IEntityPropertyDefinition = collectionDataType.Properties.Where(Function(p) p.Name.ToLower = "name").FirstOrDefault()
            If nameProperty IsNot Nothing Then
                'expression used to access collectionproperty.SelectedItem.Name
                Dim nameExpression As ChainExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id))
                host.AppendMemberExpression(nameExpression, "SelectedItem")
                host.AppendMemberExpression(nameExpression, nameProperty.Name)
                Dim namePropertyControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem,
                                                                             host.MakeUniqueLegalNameForContentItem("Name"),
                                                                             ContentItemKind.Value,
                                                                             nameExpression,
                                                                             nameProperty.PropertyType)
                host.SetControlPropertyValue(namePropertyControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            End If
// Find field called "Name".
            IEntityPropertyDefinition nameProperty = collectionDataType.Properties.Where(p => p.Name.ToLower() == "name").FirstOrDefault();
            if (nameProperty != null)
            {
                // Expression used to access collectionproperty.SelectedItem.Name
                ChainExpression nameExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id));
                host.AppendMemberExpression(nameExpression, "SelectedItem");
                host.AppendMemberExpression(nameExpression, nameProperty.Name);
                ContentItem namePropertyControl = host.AddContentItem(host.ScreenLayoutContentItem,
                                                                             host.MakeUniqueLegalNameForContentItem("Name"),
                                                                             ContentItemKind.Value,
                                                                             nameExpression,
                                                                             nameProperty.PropertyType);
                host.SetControlPropertyValue(namePropertyControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            }

如果您的目標是要顯示項目的欄位的全部或大部分,較好的選擇是建立Detail節點,並使用host.ExpandContentItem,然後如果您必須再修改結果。

Hh304432.collapse_all(zh-tw,VS.110).gif將程式碼加入至畫面

您可以使用host.AddScreenCodeBehind方法,會導致範本引擎建立時,為螢幕添照本宣科程式碼後置。 開發人員可以修改這段程式碼。 您必須提供程式碼做為特定語言的字串。 因此,您必須為每個您想要啟用的語言提供程式碼字串 (目前,C# 和Visual Basic支援)。下列範例會示範這樣做,請使用字典,其程式碼的語言會將對應到已格式化的字串,包含該語言的程式碼的一種方法。 第一,型別的本機屬性String會加入至螢幕,然後畫面,若要設定其值在後面加入程式碼InitializeDataWorkspace方法。 下列範例會示範字典,其中包含程式碼後置的Visual Basic和 C#。

Private Shared _codeTemplates As Dictionary(Of CodeLanguage, String) = New Dictionary(Of CodeLanguage, String)() From
        {
            {CodeLanguage.CSharp, _
                "" _
                + "{0}namespace {1}" _
                + "{0}{{" _
                + "{0}    public partial class {2}" _
                + "{0}    {{" _
                + "{0}" _
                + "{0}        partial void {2}_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)" _
                + "{0}        {{" _
                + "{0}            this.{3} = ""Hello World"";" _
                + "{0}        }}" _
                + "{0}" _
                + "{0}    }}" _
                + "{0}}}"
            }, _
            {CodeLanguage.VB, _
                "" _
                + "{0}Namespace {1}" _
                + "{0}" _
                + "{0}    Public Class {2}" _
                + "{0}" _
                + "{0}        Private Sub {2}_InitializeDataWorkspace(ByVal saveChangesTo As Global.System.Collections.Generic.List(Of Global.Microsoft.LightSwitch.IDataService))" _
                + "{0}            Me.{3} = ""Hello World""" _
                + "{0}        End Sub" _
                + "{0}" _
                + "{0}    End Class" _
                + "{0}" _
                + "{0}End Namespace" _
            }
        }
private static Dictionary<CodeLanguage, String> _codeTemplates = new Dictionary<CodeLanguage, String>()
        {
            {CodeLanguage.CSharp,
                ""
                + "{0}namespace {1}"
                + "{0}{{"
                + "{0}    public partial class {2}"
                + "{0}    {{"
                + "{0}"
                + "{0}        partial void {2}_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)"
                + "{0}        {{"
                + "{0}            this.{3} = \"Hello World\";"
                + "{0}        }}"
                + "{0}"
                + "{0}    }}"
                + "{0}}}"
            },
            {CodeLanguage.VB,
                ""
                + "{0}Namespace {1}"
                + "{0}"
                + "{0}    Public Class {2}"
                + "{0}"
                + "{0}        Private Sub {2}_InitializeDataWorkspace(ByVal saveChangesTo As Global.System.Collections.Generic.List(Of Global.Microsoft.LightSwitch.IDataService))"
                + "{0}            Me.{3} = \"Hello World\""
                + "{0}        End Sub"
                + "{0}"
                + "{0}    End Class"
                + "{0}"
                + "{0}End Namespace"
            }
        };

下列程式碼也會新增至Generate方法:

' Code Generation
            Dim codeTemplate As String = ""
            If _codeTemplates.TryGetValue(host.ScreenCodeBehindLanguage, codeTemplate) Then
                host.AddScreenCodeBehind(String.Format(codeTemplate,
                                                       Environment.NewLine,
                                                       host.ScreenNamespace,
                                                       host.ScreenName,
                                                       screenProperty.Name))
            End If
// Code Generation
            string codeTemplate = "";
            if (_codeTemplates.TryGetValue(host.ScreenCodeBehindLanguage, out codeTemplate))
            {
                host.AddScreenCodeBehind(String.Format(codeTemplate,
                                                       Environment.NewLine,
                                                       host.ScreenNamespace,
                                                       host.ScreenName,
                                                       screenProperty.Name));
            }

列出程式碼

以下是完整的程式碼命名為"TestTemplate",其中所有的程式碼包含在本主題中的檢測範本。

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.Composition
Imports System.Text

Imports Microsoft.LightSwitch.Designers.ScreenTemplates.Model
Imports Microsoft.LightSwitch.Model.Storage
Imports Microsoft.LightSwitch.Model
Imports System.Management

Namespace ScreenTemplates

    Public Class TestTemplate
        Implements IScreenTemplate

#Region "IScreenTemplate Members"

        Public Sub Generate(host As IScreenTemplateHost) Implements IScreenTemplate.Generate
            Dim primaryDataControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, host.MakeUniqueLegalNameForContentItem("My Root Data"), host.PrimaryDataSourceProperty)
            host.SetContentItemView(primaryDataControl, "Microsoft.LightSwitch:DataGrid")
            host.ExpandContentItem(primaryDataControl)

            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "HeightSizingMode", "Auto")
            host.SetDisplayName(primaryDataControl, "Main Screen Data")

            DirectCast(host.PrimaryDataSourceProperty, ScreenCollectionProperty).DisablePaging = True

            'Get the data type of your property
            Dim collectionProperty As ScreenCollectionProperty = DirectCast(host.PrimaryDataSourceProperty, ScreenCollectionProperty)
            Dim collectionDataType As IEntityType = host.FindGlobalModelItem(Of ISequenceType)(collectionProperty.PropertyType).ElementType

            'Create an expression that represents accessing the selected item on your collection property
            Dim chain As ChainExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id))
            host.AppendMemberExpression(chain, "SelectedItem")

            'Add a content item representing the selected item and set its view to a RowsLayout
            Dim detailControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "ItemDetail", ContentItemKind.Details, chain, collectionDataType)
            host.SetContentItemView(detailControl, "Microsoft.LightSwitch:RowsLayout")
            host.SetControlPropertyValue(detailControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            host.ExpandContentItem(detailControl)

            'Add parameters to the screen.
            Dim parameterGroup As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "ParameterGroup", ContentItemKind.Group)
            host.SetContentItemView(parameterGroup, "Microsoft.LightSwitch:ColumnsLayout")
            host.SetControlPropertyValue(parameterGroup, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            For Each param As ScreenPropertyBase In host.PrimaryDataSourceParameterProperties
                host.AddContentItem(parameterGroup, param.Name, param)
            Next

            'Find field called "Name".
            Dim nameProperty As IEntityPropertyDefinition = collectionDataType.Properties.Where(Function(p) p.Name.ToLower = "name").FirstOrDefault()
            If nameProperty IsNot Nothing Then
                'expression used to access collectionproperty.SelectedItem.Name
                Dim nameExpression As ChainExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id))
                host.AppendMemberExpression(nameExpression, "SelectedItem")
                host.AppendMemberExpression(nameExpression, nameProperty.Name)
                Dim namePropertyControl As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem,
                                                                             host.MakeUniqueLegalNameForContentItem("Name"),
                                                                             ContentItemKind.Value,
                                                                             nameExpression,
                                                                             nameProperty.PropertyType)
                host.SetControlPropertyValue(namePropertyControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top")
            End If

            'Add a tabs group to the screen.
            Dim tabsGroup As ContentItem = host.AddContentItem(host.ScreenLayoutContentItem, "TabsGroup", ContentItemKind.Group)
            host.SetContentItemView(tabsGroup, "Microsoft.LightSwitch:TabsLayout")

            For Each p As ScreenCollectionProperty In host.ChildCollectionProperties
                'Display each child collection as a grid
                Dim currentTab As ContentItem = host.AddContentItem(tabsGroup, host.MakeUniqueLegalNameForContentItem("Tab"), p)
                host.SetContentItemView(currentTab, "Microsoft.LightSwitch:DataGrid")
                host.ExpandContentItem(currentTab)
            Next

            'Add a screen member.
            Dim screenProperty As ScreenProperty = host.AddScreenProperty("Microsoft.LightSwitch:String", "NewScreenProperty")

            'Code Generation
            Dim codeTemplate As String = ""
            If _codeTemplates.TryGetValue(host.ScreenCodeBehindLanguage, codeTemplate) Then
                host.AddScreenCodeBehind(String.Format(codeTemplate,
                                                       Environment.NewLine,
                                                       host.ScreenNamespace,
                                                       host.ScreenName,
                                                       screenProperty.Name))
            End If



        End Sub

        Private Shared _codeTemplates As Dictionary(Of CodeLanguage, String) = New Dictionary(Of CodeLanguage, String)() From
        {
            {CodeLanguage.CSharp, _
                "" _
                + "{0}namespace {1}" _
                + "{0}{{" _
                + "{0}    public partial class {2}" _
                + "{0}    {{" _
                + "{0}" _
                + "{0}        partial void {2}_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)" _
                + "{0}        {{" _
                + "{0}            this.{3} = ""Hello World"";" _
                + "{0}        }}" _
                + "{0}" _
                + "{0}    }}" _
                + "{0}}}"
            }, _
            {CodeLanguage.VB, _
                "" _
                + "{0}Namespace {1}" _
                + "{0}" _
                + "{0}    Public Class {2}" _
                + "{0}" _
                + "{0}        Private Sub {2}_InitializeDataWorkspace(ByVal saveChangesTo As Global.System.Collections.Generic.List(Of Global.Microsoft.LightSwitch.IDataService))" _
                + "{0}            Me.{3} = ""Hello World""" _
                + "{0}        End Sub" _
                + "{0}" _
                + "{0}    End Class" _
                + "{0}" _
                + "{0}End Namespace" _
            }
        }

        Public ReadOnly Property Description As String Implements IScreenTemplateMetadata.Description
            Get
                Return "Test Template Description"
            End Get
        End Property

        Public ReadOnly Property DisplayName As String Implements IScreenTemplateMetadata.DisplayName
            Get
                Return "Test Template"
            End Get
        End Property

        Public ReadOnly Property PreviewImage As Uri Implements IScreenTemplateMetadata.PreviewImage
            Get
                Return New Uri("/ScreenTemplateExtension.Design;component/Resources/ScreenTemplateImages/TestTemplateLarge.png", UriKind.Relative)
            End Get
        End Property

        Public ReadOnly Property RootDataSource As RootDataSourceType Implements IScreenTemplateMetadata.RootDataSource
            Get
                Return RootDataSourceType.Collection
            End Get
        End Property

        Public ReadOnly Property ScreenNameFormat As String Implements IScreenTemplateMetadata.ScreenNameFormat
            Get
                Return "{0}TestTemplate"
            End Get
        End Property

        Public ReadOnly Property SmallIcon As Uri Implements IScreenTemplateMetadata.SmallIcon
            Get
                Return New Uri("/ScreenTemplateExtension.Design;component/Resources/ScreenTemplateImages/TestTemplateSmall.png", UriKind.Relative)
            End Get
        End Property

        Public ReadOnly Property SupportsChildCollections As Boolean Implements IScreenTemplateMetadata.SupportsChildCollections
            Get
                Return True
            End Get
        End Property

        Public ReadOnly Property TemplateName As String Implements IScreenTemplateMetadata.TemplateName
            Get
                Return TestTemplate.TemplateId
            End Get
        End Property

#End Region

#Region "Constants"

        Friend Const TemplateId As String = "ScreenTemplateExtension:TestTemplate"

#End Region

    End Class

    <Export(GetType(IScreenTemplateFactory))>
    <Template(TestTemplate.TemplateId)>
    Friend Class TestTemplateFactory
        Implements IScreenTemplateFactory

#Region "IScreenTemplateFactory Members"

        Public Function CreateScreenTemplate() As IScreenTemplate Implements IScreenTemplateFactory.CreateScreenTemplate
            Return New TestTemplate()
        End Function

#End Region

    End Class

End Namespace
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Management;
using System.Text;

using Microsoft.LightSwitch.Designers.ScreenTemplates.Model;
using Microsoft.LightSwitch.Model;
using Microsoft.LightSwitch.Model.Storage;

namespace ScreenTemplateExtension.ScreenTemplates
{
    public class TestTemplate : IScreenTemplate
    {
        #region IScreenTemplate Members

        public void Generate(IScreenTemplateHost host)
        {
            ContentItem primaryDataControl = host.AddContentItem(host.ScreenLayoutContentItem, host.MakeUniqueLegalNameForContentItem("My Root Data"), host.PrimaryDataSourceProperty);
            host.SetContentItemView(primaryDataControl, "Microsoft.LightSwitch:DataGrid");
            host.ExpandContentItem(primaryDataControl);

            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            host.SetControlPropertyValue(primaryDataControl, "Microsoft.LightSwitch:RootControl", "HeightSizingMode", "Auto");
            host.SetDisplayName(primaryDataControl, "Main Screen Data");

            ((ScreenCollectionProperty)host.PrimaryDataSourceProperty).DisablePaging = true;

            // Get the data type of your property.
            ScreenCollectionProperty collectionProperty = (ScreenCollectionProperty)(host.PrimaryDataSourceProperty);
            IEntityType collectionDataType = host.FindGlobalModelItem<ISequenceType>(collectionProperty.PropertyType).ElementType as IEntityType;

            // Create an expression that represents accessing the selected item on your collection property.
            ChainExpression chain = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id));
            host.AppendMemberExpression(chain, "SelectedItem");

            // Add a content item representing the selected item and set its view to a RowsLayout.
            ContentItem detailControl = host.AddContentItem(host.ScreenLayoutContentItem, "ItemDetail", ContentItemKind.Details, chain, collectionDataType);
            host.SetContentItemView(detailControl, "Microsoft.LightSwitch:RowsLayout");
            host.SetControlPropertyValue(detailControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            host.ExpandContentItem(detailControl);

            // Add parameters to the screen.
            ContentItem parameterGroup = host.AddContentItem(host.ScreenLayoutContentItem, "ParameterGroup", ContentItemKind.Group);
            host.SetContentItemView(parameterGroup, "Microsoft.LightSwitch:ColumnsLayout");
            host.SetControlPropertyValue(parameterGroup, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            foreach (ScreenPropertyBase param in host.PrimaryDataSourceParameterProperties)
            {
                host.AddContentItem(parameterGroup, param.Name, param);
            }

            // Find field called "Name".
            IEntityPropertyDefinition nameProperty = collectionDataType.Properties.Where(p => p.Name.ToLower() == "name").FirstOrDefault();
            if (nameProperty != null)
            {
                // Expression used to access collectionproperty.SelectedItem.Name
                ChainExpression nameExpression = host.CreateChainExpression(host.CreateMemberExpression(collectionProperty.Id));
                host.AppendMemberExpression(nameExpression, "SelectedItem");
                host.AppendMemberExpression(nameExpression, nameProperty.Name);
                ContentItem namePropertyControl = host.AddContentItem(host.ScreenLayoutContentItem,
                                                                             host.MakeUniqueLegalNameForContentItem("Name"),
                                                                             ContentItemKind.Value,
                                                                             nameExpression,
                                                                             nameProperty.PropertyType);
                host.SetControlPropertyValue(namePropertyControl, "Microsoft.LightSwitch:RootControl", "VerticalAlignment", "Top");
            }

            // Add a tabs group to the screen.
            ContentItem tabsGroup = host.AddContentItem(host.ScreenLayoutContentItem, "TabsGroup", ContentItemKind.Group);
            host.SetContentItemView(tabsGroup, "Microsoft.LightSwitch:TabsLayout");

            foreach (ScreenCollectionProperty p in host.ChildCollectionProperties)
            {
                // Display each child collection as a grid.
                ContentItem currentTab = host.AddContentItem(tabsGroup, host.MakeUniqueLegalNameForContentItem("Tab"), p);
                host.SetContentItemView(currentTab, "Microsoft.LightSwitch:DataGrid");
                host.ExpandContentItem(currentTab);
            }

            // Add a screen member.
            ScreenProperty screenProperty = host.AddScreenProperty("Microsoft.LightSwitch:String", "NewScreenProperty") as ScreenProperty;

            // Code Generation
            string codeTemplate = "";
            if (_codeTemplates.TryGetValue(host.ScreenCodeBehindLanguage, out codeTemplate))
            {
                host.AddScreenCodeBehind(String.Format(codeTemplate,
                                                       Environment.NewLine,
                                                       host.ScreenNamespace,
                                                       host.ScreenName,
                                                       screenProperty.Name));
            }
        }

        private static Dictionary<CodeLanguage, String> _codeTemplates = new Dictionary<CodeLanguage, String>()
        {
            {CodeLanguage.CSharp,
                ""
                + "{0}namespace {1}"
                + "{0}{{"
                + "{0}    public partial class {2}"
                + "{0}    {{"
                + "{0}"
                + "{0}        partial void {2}_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)"
                + "{0}        {{"
                + "{0}            this.{3} = \"Hello World\";"
                + "{0}        }}"
                + "{0}"
                + "{0}    }}"
                + "{0}}}"
            },
            {CodeLanguage.VB,
                ""
                + "{0}Namespace {1}"
                + "{0}"
                + "{0}    Public Class {2}"
                + "{0}"
                + "{0}        Private Sub {2}_InitializeDataWorkspace(ByVal saveChangesTo As Global.System.Collections.Generic.List(Of Global.Microsoft.LightSwitch.IDataService))"
                + "{0}            Me.{3} = \"Hello World\""
                + "{0}        End Sub"
                + "{0}"
                + "{0}    End Class"
                + "{0}"
                + "{0}End Namespace"
            }
        };

        public string Description
        {
            get { return "TestTemplate Description"; }
        }

        public string DisplayName
        {
            get { return "Test Template"; }
        }

        public Uri PreviewImage
        {
            get { return new Uri("/ScreenTemplateExtension.Design;component/Resources/ScreenTemplateImages/TestTemplateLarge.png", UriKind.Relative); }
        }

        public RootDataSourceType RootDataSource
        {
            get { return RootDataSourceType.Collection; }
        }

        public string ScreenNameFormat
        {
            get { return "{0}TestTemplate"; }
        }

        public Uri SmallIcon
        {
            get { return new Uri("/ScreenTemplateExtension.Design;component/Resources/ScreenTemplateImages/TestTemplateSmall.png", UriKind.Relative); }
        }

        public bool SupportsChildCollections
        {
            get { return true; }
        }

        public string TemplateName
        {
            get { return TestTemplate.TemplateId; }
        }

        #endregion

        #region Constants

        internal const string TemplateId = "ScreenTemplateExtension:TestTemplate";

        #endregion
    }

    [Export(typeof(IScreenTemplateFactory))]
    [Template(TestTemplate.TemplateId)]
    internal class TestTemplateFactory : IScreenTemplateFactory
    {
        #region IScreenTemplateFactory Members

        IScreenTemplate IScreenTemplateFactory.CreateScreenTemplate()
        {
            return new TestTemplate();
        }

        #endregion
    }
}

請參閱

工作

HOW TO:偵錯或測試 LightSwitch 擴充功能

HOW TO:建立 LightSwitch 擴充功能專案

概念

LightSwitch 控制項 ViewID

定義、覆寫和使用 LightSwitch 控制項屬性

Visual Studio 2012 的 LightSwitch 擴充性工具組