共用方式為


使用 ModelItem 編輯內容

ModelItem 編輯內容是主機應用程式用來與設計工具通訊的物件。 EditingContext 公開兩個可使用的方法:ItemsServices

Items 集合

Items 集合是用來存取在主機與設計工具之間共用的資料,或是提供給所有設計工具的資料。 這個集合具有下列功能 (經由 ContextItemManager 類別存取):

  1. GetValue

  2. Subscribe

  3. Unsubscribe

  4. SetValue

Services 集合

Services 集合是用來存取設計工具與主機互動所用的服務,或是所有設計工具使用的服務。 這個集合具有下列重要方法:

  1. Publish

  2. Subscribe

  3. Unsubscribe

  4. GetService

將活動指派給設計工具

若要指定活動所使用的設計工具,請使用 Designer 屬性。

[Designer(typeof(MyClassDesigner))]  
public sealed class MyClass : CodeActivity  
{
}

建立服務

若要建立在設計工具與主機之間當做資訊管道的服務,您必須建立介面和實作。 Publish 方法會使用此介面來定義服務的成員,而且此實作包含服務的邏輯。 在下列程式碼範例中,系統會建立服務介面和實作。

public interface IMyService  
    {  
        IEnumerable<string> GetValues(string DisplayName);  
    }  
  
    public class MyServiceImpl : IMyService  
    {  
        public IEnumerable<string> GetValues(string DisplayName)  
        {  
            return new string[]  {
                DisplayName + " One",
                DisplayName + " Two",  
                "Three " + DisplayName  
            } ;  
        }  
    }  

發行服務

為了讓設計工具取用服務,主機必須先使用 Publish 方法來發行服務。

this.Context.Services.Publish<IMyService>(new MyServiceImpl);  

訂閱服務

設計工具會使用 Subscribe 方法中的 OnModelItemChanged 方法來取得服務的存取權。 下列程式碼片段示範如何訂閱服務。

protected override void OnModelItemChanged(object newItem)  
{  
    if (!subscribed)  
    {  
        this.Context.Services.Subscribe<IMyService>(  
            servInstance =>  
            {  
                listBox1.ItemsSource = servInstance.GetValues(this.ModelItem.Properties["DisplayName"].ComputedValue.ToString());  
            }  
            );  
        subscribed = true;
    }  
}  

使用 Items 集合共用資料

使用 Items 集合與使用 Services 集合很相似,不過 SetValue 會用來取代 Publish。 這個集合比較適合在設計工具與主機之間共用簡單的資料,而非複雜的功能。

EditingContext 主機項目和服務

.NET Framework 提供了許多透過編輯內容存取的內建項目和服務。

Items:

服務: