ConsumerConnectionPoint 类

定义

定义连接点对象,该对象允许服务器控件作为使用者,以建立与提供者的连接。Defines a connection point object that enables a server control acting as a consumer to form a connection with a provider.

public ref class ConsumerConnectionPoint : System::Web::UI::WebControls::WebParts::ConnectionPoint
public class ConsumerConnectionPoint : System.Web.UI.WebControls.WebParts.ConnectionPoint
type ConsumerConnectionPoint = class
    inherit ConnectionPoint
Public Class ConsumerConnectionPoint
Inherits ConnectionPoint
继承
ConsumerConnectionPoint

示例

下面的代码示例演示了使用使用者连接点的每种情况下, 以声明方式、编程方式或通过 UI 创建连接的简单方法。The following code example shows simple ways to create a connection declaratively, programmatically, or through the UI, in each case making use of a consumer connection point.

该示例包含四个部分:The example has four parts:

  • 允许您在页上更改 Web 部件显示模式的用户控件。A user control that enables you to change the Web Parts display mode on a page.

  • 接口的源代码和两个WebPart用作连接的提供者和使用者的控件。Source code for an interface and two WebPart controls acting as the provider and the consumer for a connection.

  • 承载所有控件并运行代码示例的网页。A Web page to host all the controls and run the code example.

  • 有关如何运行 "示例" 页的说明。An explanation of how to run the example page.

此代码示例的第一部分是用户控件, 该控件使用户能够更改网页上的显示模式。The first part of this code example is the user control that enables users to change display modes on a Web page. 将以下源代码保存到 .ascx 文件, 并为其提供分配给Src此用户控件的Register指令属性的文件名, 该属性位于宿主网页的顶部附近。Save the following source code to an .ascx file, giving it the file name that is assigned to the Src attribute of the Register directive for this user control, which is near the top of the hosting Web page. 有关显示模式的详细信息以及此控件中源代码的说明, 请参阅演练:更改 Web 部件页上的显示模式。For details about display modes and a description of the source code in this control, see Walkthrough: Changing Display Modes on a Web Parts Page.

<%@ control language="C#" classname="DisplayModeMenuCS"%>
<script runat="server">
  
 // Use a field to reference the current WebPartManager.
  WebPartManager _manager;

  void Page_Init(object sender, EventArgs e)
  {
    Page.InitComplete += new EventHandler(InitComplete);
  }  

  void InitComplete(object sender, System.EventArgs e)
  {
    _manager = WebPartManager.GetCurrentWebPartManager(Page);

    String browseModeName = WebPartManager.BrowseDisplayMode.Name;

    // Fill the dropdown with the names of supported display modes.
    foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes)
    {
      String modeName = mode.Name;
      // Make sure a mode is enabled before adding it.
      if (mode.IsEnabled(_manager))
      {
        ListItem item = new ListItem(modeName, modeName);
        DisplayModeDropdown.Items.Add(item);
      }
    }

    // If shared scope is allowed for this user, display the scope-switching
    // UI and select the appropriate radio button for the current user scope.
    if (_manager.Personalization.CanEnterSharedScope)
    {
      Panel2.Visible = true;
      if (_manager.Personalization.Scope == PersonalizationScope.User)
        RadioButton1.Checked = true;
      else
        RadioButton2.Checked = true;
    }
    
  }
 
  // Change the page to the selected display mode.
  void DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e)
  {
    String selectedMode = DisplayModeDropdown.SelectedValue;

    WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode];
    if (mode != null)
      _manager.DisplayMode = mode;
  }

  // Set the selected item equal to the current display mode.
  void Page_PreRender(object sender, EventArgs e)
  {
    ListItemCollection items = DisplayModeDropdown.Items;
    int selectedIndex = 
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
    DisplayModeDropdown.SelectedIndex = selectedIndex;
  }

  // Reset all of a user's personalization data for the page.
  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    _manager.Personalization.ResetPersonalizationState();
  }

  // If not in User personalization scope, toggle into it.
  protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.Scope == PersonalizationScope.Shared)
      _manager.Personalization.ToggleScope();
  }

  // If not in Shared scope, and if user is allowed, toggle the scope.
  protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.CanEnterSharedScope && 
        _manager.Personalization.Scope == PersonalizationScope.User)
      _manager.Personalization.ToggleScope();
  }
</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text="&nbsp;Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>
<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
  ' Use a field to reference the current WebPartManager.
  Dim _manager As WebPartManager

  Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    AddHandler Page.InitComplete, AddressOf InitComplete
  End Sub

  Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)
    _manager = WebPartManager.GetCurrentWebPartManager(Page)
      
    Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
      
    ' Fill the dropdown with the names of supported display modes.
    Dim mode As WebPartDisplayMode
    For Each mode In _manager.SupportedDisplayModes
      Dim modeName As String = mode.Name
      ' Make sure a mode is enabled before adding it.
      If mode.IsEnabled(_manager) Then
        Dim item As New ListItem(modeName, modeName)
        DisplayModeDropdown.Items.Add(item)
      End If
    Next mode
      
    ' If shared scope is allowed for this user, display the scope-switching
    ' UI and select the appropriate radio button for the current user scope.
    If _manager.Personalization.CanEnterSharedScope Then
      Panel2.Visible = True
      If _manager.Personalization.Scope = PersonalizationScope.User Then
        RadioButton1.Checked = True
      Else
        RadioButton2.Checked = True
      End If
    End If
   
  End Sub

  ' Change the page to the selected display mode.
  Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    Dim selectedMode As String = DisplayModeDropdown.SelectedValue   
    Dim mode As WebPartDisplayMode = _
      _manager.SupportedDisplayModes(selectedMode)
    If Not (mode Is Nothing) Then
      _manager.DisplayMode = mode
    End If

  End Sub
   
  ' Set the selected item equal to the current display mode.
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    Dim items As ListItemCollection = DisplayModeDropdown.Items
    Dim selectedIndex As Integer = _
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name))
    DisplayModeDropdown.SelectedIndex = selectedIndex

  End Sub

  ' Reset all of a user's personalization data for the page.
  Protected Sub LinkButton1_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    _manager.Personalization.ResetPersonalizationState()
    
  End Sub

  ' If not in User personalization scope, toggle into it.
  Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.Scope = PersonalizationScope.Shared Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub
   
  ' If not in Shared scope, and if user is allowed, toggle the scope.
  Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.CanEnterSharedScope AndAlso _
      _manager.Personalization.Scope = PersonalizationScope.User Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub

</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text="&nbsp;Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>

此代码示例的第二部分是接口和控件的源代码。The second part of the code example is the source code for the interface and controls. 源文件包含一个名为IZipCode的简单接口。The source file contains a simple interface named IZipCode. 还有一个WebPart名为ZipCodeWebPart的类, 该类实现接口并充当提供程序控件。There is also a WebPart class named ZipCodeWebPart that implements the interface and acts as the provider control. 其他WebPart类命名WeatherWebPart为, 它充当连接的使用者。The other WebPart class is named WeatherWebPart, and it acts as the consumer for the connection. 此类具有一个名为GetZipCode的方法, 该方法从IZipCode提供程序控件获取接口的实例。This class has a method named GetZipCode that gets an instance of the IZipCode interface from the provider control. 请注意, 此方法在其元数据中被标记为使用者ConnectionConsumer的连接点方法和属性。Note that this method is marked as the consumer's connection point method with a ConnectionConsumer attribute in its metadata. 这是用于标识使用者控件中的连接点方法的机制。This is the mechanism for identifying the connection point method in the consumer control.

要使代码示例运行, 必须编译此源代码。For the code example to run, you must compile this source code. 可以显式编译该程序集, 并将生成的程序集放在网站的 Bin 文件夹或全局程序集缓存中。You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. 或者, 你可以将源代码放在站点的 App_Code 文件夹中, 在此文件夹中, 它将在运行时动态编译。Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. 此代码示例使用动态编译。This code example uses dynamic compilation. 有关演示如何编译的演练, 请参阅演练:开发和使用自定义 Web 服务器控件For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

namespace Samples.AspNet.CS.Controls
{
  using System;
  using System.Web;
  using System.Web.Security;
  using System.Security.Permissions;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public interface IZipCode
  {
    string ZipCode { get; set;}
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class ZipCodeWebPart : WebPart, IZipCode
  {
    string zipCodeText = String.Empty;
    TextBox input;
    Button send;

    public ZipCodeWebPart()
    {
    }

    // Make the implemented property personalizable to save 
    // the Zip Code between browser sessions.
    [Personalizable()]
    public virtual string ZipCode
    {
      get { return zipCodeText; }
      set { zipCodeText = value; }
    }

    // This is the callback method that returns the provider.
    [ConnectionProvider("Zip Code Provider", "ZipCodeProvider")]
    public IZipCode ProvideIZipCode()
    {
      return this;
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      input = new TextBox();
      this.Controls.Add(input);
      send = new Button();
      send.Text = "Enter 5-digit Zip Code";
      send.Click += new EventHandler(this.submit_Click);
      this.Controls.Add(send);
    }

    private void submit_Click(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(input.Text))
      {
        zipCodeText = Page.Server.HtmlEncode(input.Text);
        input.Text = String.Empty;
      }
    }
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class WeatherWebPart : WebPart
  {
    private IZipCode _provider;
    string _zipSearch;
    Label DisplayContent;

    // This method is identified by the ConnectionConsumer 
    // attribute, and is the mechanism for connecting with 
    // the provider. 
    [ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")]
    public void GetIZipCode(IZipCode Provider)
    {
      _provider = Provider;
    }
    
    protected override void OnPreRender(EventArgs e)
    {
      EnsureChildControls();

      if (this._provider != null)
      {
        _zipSearch = _provider.ZipCode.Trim();
        DisplayContent.Text = "My Zip Code is:  " + _zipSearch;
      }
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      DisplayContent = new Label();
      this.Controls.Add(DisplayContent);
    }
  }
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Interface IZipCode

    Property ZipCode() As String

  End Interface

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class ZipCodeWebPart
    Inherits WebPart
    Implements IZipCode
    Private zipCodeText As String = String.Empty
    Private input As TextBox
    Private send As Button

    Public Sub New()
    End Sub

    ' Make the implemented property personalizable to save 
    ' the Zip Code between browser sessions.
    <Personalizable()> _
    Public Property ZipCode() As String _
      Implements IZipCode.ZipCode

      Get
        Return zipCodeText
      End Get
      Set(ByVal value As String)
        zipCodeText = value
      End Set
    End Property

    ' This is the callback method that returns the provider.
    <ConnectionProvider("Zip Code Provider", "ZipCodeProvider")> _
    Public Function ProvideIZipCode() As IZipCode
      Return Me
    End Function


    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      input = New TextBox()
      Me.Controls.Add(input)
      send = New Button()
      send.Text = "Enter 5-digit Zip Code"
      AddHandler send.Click, AddressOf Me.submit_Click
      Me.Controls.Add(send)

    End Sub


    Private Sub submit_Click(ByVal sender As Object, _
      ByVal e As EventArgs)

      If input.Text <> String.Empty Then
        zipCodeText = Page.Server.HtmlEncode(input.Text)
        input.Text = String.Empty
      End If

    End Sub

  End Class

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class WeatherWebPart
    Inherits WebPart
    Private _provider As IZipCode
    Private _zipSearch As String
    Private DisplayContent As Label

    ' This method is identified by the ConnectionConsumer 
    ' attribute, and is the mechanism for connecting with 
    ' the provider. 
    <ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")> _
    Public Sub GetIZipCode(ByVal Provider As IZipCode)
      _provider = Provider
    End Sub


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      EnsureChildControls()

      If Not (Me._provider Is Nothing) Then
        _zipSearch = _provider.ZipCode.Trim()
                DisplayContent.Text = "My Zip Code is:  " + _zipSearch
      End If

    End Sub

    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      DisplayContent = New Label()
      Me.Controls.Add(DisplayContent)

    End Sub

  End Class

End Namespace

此代码示例的第三部分是网页。The third part of the code example is the Web page. 顶部附近是Register注册构成连接的自定义控件的指令, 以及允许用户在页面上更改显示模式的用户控件。Near the top are Register directives to register the custom controls that form the connection, and the user control that enables users to change display modes on the page. 连接本身是在页面上的<staticconnections>元素中以声明方式创建的。The connection itself is created declaratively within the <staticconnections> element on the page. 这说明了创建连接的一种方法--请ConsumerConnectionPointID注意<asp:webpartconnection>元素中的属性。This demonstrates one way of creating a connection--note the ConsumerConnectionPointID attribute in the <asp:webpartconnection> element. 还可以通过编程方式创建连接;用于执行此操作的代码位于Button1_Click方法中。You can also create the connection programmatically; the code for doing that is in the Button1_Click method. 在这种情况下ConsumerConnectionPoint , 将创建一个对象, 然后将该对象传递给创建实际连接的方法。In this case, a ConsumerConnectionPoint object is created and then passed to a method that creates the actual connection. 无论连接是以声明方式创建还是以编程方式创建, 都必须始终为提供程序和使用者指定连接点。Whether the connection is created declaratively or programmatically, connection points must always be specified for both the provider and the consumer. 方法访问提供程序ConnectionPoint和使用者的对象, 并将其一些属性值写入页中的标签。 Button2_ClickThe Button2_Click method accesses the ConnectionPoint objects for both the provider and the consumer, and writes some of their property values to a label in the page.

<%@ Page Language="C#" %>
<%@ register tagprefix="uc1" 
    tagname="DisplayModeMenuCS"
    src="~/displaymodemenucs.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.CS.Controls" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void Button1_Click(object sender, EventArgs e)
  {
    ProviderConnectionPoint provPoint =
      mgr.GetProviderConnectionPoints(zip1)["ZipCodeProvider"];
    ConsumerConnectionPoint connPoint =
      mgr.GetConsumerConnectionPoints(weather1)["ZipCodeConsumer"];
      
    if(mgr.CanConnectWebParts(zip1, provPoint, weather1, connPoint))
      mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint);
  
  }  
  protected void Button2_Click(object sender, EventArgs e)
  {
    WebPartConnection conn = mgr.Connections[0];
    
    lblConn.Text = "<h2>Connection Point Details</h2>" + 
       "<h3>Provider Connection Point</h3>" + 
       "  Display name: " + conn.ProviderConnectionPoint.DisplayName + 
       "<br />" + 
       "  ID: " + conn.ProviderConnectionPoint.ID + 
       "<br />" + 
       "  Interface type: " + 
        conn.ProviderConnectionPoint.InterfaceType.ToString() + 
       "<br />" + 
       "  Control type: " + conn.ProviderConnectionPoint.ControlType.ToString() + 
       "<br />" + 
       "  Allows multiple connections: " + 
          conn.ProviderConnectionPoint.AllowsMultipleConnections.ToString() + 
       "<br />" + 
       "  Enabled: " + conn.ProviderConnectionPoint.GetEnabled(zip1).ToString() + 
       "<hr />" + 
       "<h3>Consumer Connection Point</h3>" + 
       "  Display name: " + conn.ConsumerConnectionPoint.DisplayName + 
       "<br />" + 
       "  ID: " + conn.ConsumerConnectionPoint.ID + 
       "<br />" + 
       "  Interface type: " + conn.ConsumerConnectionPoint.InterfaceType.ToString() + 
       "<br />" + 
       "  Control type: " + conn.ConsumerConnectionPoint.ControlType.ToString() + 
       "<br />" + 
       "  Allows multiple connections: " + 
          conn.ConsumerConnectionPoint.AllowsMultipleConnections.ToString() + 
       "<br />" + 
       "  Enabled: " + conn.ConsumerConnectionPoint.GetEnabled(zip1).ToString();
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    lblConn.Text = String.Empty;
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server" >
        <StaticConnections>
          <asp:WebPartConnection ID="conn1"
            ConsumerConnectionPointID="ZipCodeConsumer"
            ConsumerID="weather1" 
            ProviderConnectionPointID="ZipCodeProvider" 
            ProviderID="zip1" />
        </StaticConnections>      
      </asp:WebPartManager>
      <uc1:displaymodemenucs id="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider"  />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Dynamic Connection" 
        OnClick="Button1_Click" />      
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="Connection Point Details" 
        OnClick="Button2_Click" />
      <br />
      <asp:Label ID="lblConn" runat="server" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ register tagprefix="uc1" 
    tagname="DisplayModeMenuVB"
    src="~/displaymodemenuvb.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.VB.Controls" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)

    Dim provPoint As ProviderConnectionPoint = _
      mgr.GetProviderConnectionPoints(zip1)("ZipCodeProvider")
    Dim connPoint As ConsumerConnectionPoint = _
      mgr.GetConsumerConnectionPoints(weather1)("ZipCodeConsumer")

    If mgr.CanConnectWebParts(zip1, provPoint, weather1, connPoint) Then
      mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint)
    End If
    
  End Sub
  
  Protected Sub Button2_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim conn As WebPartConnection = mgr.Connections(0)

    lblConn.Text = "<h2>Connection Point Details</h2>" & _
      "<h3>Provider Connection Point</h3>" & _
      "  Display name: " & conn.ProviderConnectionPoint.DisplayName & _
      "<br />" & _
      "  ID: " & conn.ProviderConnectionPoint.ID & _
      "<br />" & _
      "  Interface type: " & conn.ProviderConnectionPoint.InterfaceType.ToString() & _
      "<br />" & _
      "  Control type: " & conn.ProviderConnectionPoint.ControlType.ToString() & _
      "<br />" & _
      "  Allows multiple connections: " & _
        conn.ProviderConnectionPoint.AllowsMultipleConnections.ToString() & _
      "<br />" & _
      "  Enabled: " & conn.ProviderConnectionPoint.GetEnabled(zip1).ToString() & _
      "<hr />" & _
      "<h3>Consumer Connection Point</h3>" & _
      "  Display name: " & conn.ConsumerConnectionPoint.DisplayName & _
      "<br />" & _
      "  ID: " & conn.ConsumerConnectionPoint.ID & _
      "<br />" & _
      "  Interface type: " & conn.ConsumerConnectionPoint.InterfaceType.ToString() & _
      "<br />" & _
      "  Control type: " & conn.ConsumerConnectionPoint.ControlType.ToString() & _
      "<br />" & _
      "  Allows multiple connections: " & _
        conn.ConsumerConnectionPoint.AllowsMultipleConnections.ToString() & _
      "<br />" & _
      "  Enabled: " & conn.ConsumerConnectionPoint.GetEnabled(zip1).ToString()
          
  End Sub

  Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    lblConn.Text = String.Empty
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server" >
        <StaticConnections>
          <asp:WebPartConnection ID="conn1"
            ConsumerConnectionPointID="ZipCodeConsumer"
            ConsumerID="weather1" 
            ProviderConnectionPointID="ZipCodeProvider" 
            ProviderID="zip1" />
        </StaticConnections>      
      </asp:WebPartManager>
      <uc1:displaymodemenuvb id="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider"  />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Dynamic Connection" 
        OnClick="Button1_Click" />      
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="Connection Point Details" 
        OnClick="Button2_Click" />
      <br />
      <asp:Label ID="lblConn" runat="server" />
    </div>
    </form>
</body>
</html>

在浏览器中加载页面后, 单击 "连接点详细信息" 按钮。After you load the page in a browser, click the Connection Point Details button. 此时将显示有关在声明性连接中建立的提供者和使用者连接点的信息。Information about the provider and consumer connection points established in the declarative connection appears. 接下来, 使用 "显示模式" 下拉控件将页面切换到连接模式。Next, use the Display Mode drop-down control to switch the page into connect mode. 邮政编码提供程序WebPart控件 (由标题栏中的向下箭头表示) 的谓词菜单上, 单击 "连接" 谓词。On the verbs menu of the ZIP Code ProviderWebPart control (represented by a downward arrow in the title bar), click the connect verb. 连接 UI 随即出现, 由<asp:connectionszone>页面中声明的控件自动创建。The connection UI appears, created automatically by the <asp:connectionszone> control declared in the page. 这是创建连接的另一种方法 (通过 UI) 以及前面讨论的声明性和编程方法。This is another way of creating a connection (through the UI), along with the declarative and programmatic methods discussed earlier. 单击 "断开连接" 按钮以终止现有静态连接。Click the Disconnect button to terminate the existing static connection. 单击 "创建使用者连接" 链接。Click the Create a Connection to a Consumer link. UI 现在会显示一个下拉列表控件, 其中列出了使用者连接点显示名称。The UI now displays a drop-down control that lists the consumer connection point display name. 在下拉列表中选择连接点, 然后单击 "连接" 以完成连接。Select the connection point in the drop-down list, and then click Connect to complete the connection. 接下来, 再次单击 "断开"。Next, click Disconnect again. 单击 "动态连接" 按钮以编程方式创建连接。Click the Dynamic Connection button to create a connection programmatically. 使用 "显示模式" 控件将页面返回到浏览模式。Use the Display Mode control to return the page to browse mode. 再次单击 "连接点详细信息" 按钮, 以指示有关使用者连接点对象的详细信息。Click the Connection Point Details button again, to indicate details about the consumer connection point object once more.

该示例演示了如何建立连接并以三种方式使用使用者连接点: 在网页标记中声明的静态连接;在使用ConsumerConnectionPoint对象的代码中创建的连接; 通过连接 UI 创建的连接。The example has demonstrated establishing a connection and using a consumer connection point in three ways: a static connection declared in the Web page markup; a connection created in code that used a ConsumerConnectionPoint object; and a connection created by a user through the connection UI.

注解

在两个服务器控件之间的每个 Web 部件连接中, 每个控件都必须具有关联的连接点对象, 该对象使其能够连接到其他控件并提供或使用数据, 具体取决于控件是否指定为连接的提供者或使用者。In every Web Parts connection between two server controls, each control must have (among other requirements) an associated connection point object that enables it to connect to the other control and to either provide or consume data, depending on whether the control is designated as the provider or consumer for the connection. ConnectionPoint对象通常包含有关控件如何连接到其他控件的详细信息以及它可以共享的数据类型的详细信息。A ConnectionPoint object in general contains the details for how a control can connect to another control and the type of data it can share. 对于在连接中充当使用者的控件, 其连接点必须是ConsumerConnectionPoint对象。For a control acting as the consumer in a connection, its connection point must be a ConsumerConnectionPoint object. 有关 Web 部件连接和连接点的详细信息, 请阅读下面的 "另请参阅" 部分中列出的主题。For details on Web Parts connections and connection points, read the topics listed in the See Also section below.

若要创建ConsumerConnectionPoint对象, 需要执行多个步骤:To create a ConsumerConnectionPoint object, several steps are required:

  1. 允许使用者控件引用接口实例。Enable a consumer control to reference an interface instance. 或其他服务器控件 (可以使用将添加WebPartZoneBase到区域的服务器控件的任何类型) 都必须能够使用特定接口实例中的数据。 WebPartA WebPart or other server control (any type of server control that will be added to a WebPartZoneBase zone can be used) must be able to consume data from a specific interface instance. 控件无需实现接口;只有提供程序必须实现它。The control need not implement the interface; only the provider must implement it. 使用者可以使用提供程序提供的准确接口类型, 如果不是, WebPartTransformer则可以使用对象将数据从提供程序的接口类型转换为使用者识别的类型。The consumer can either work with the exact interface type served by a provider or, if it does not, a WebPartTransformer object can be used to transform data from a provider's interface type to a type understood by the consumer. 启用使用者的典型方法是声明私有字段, 使其包含对所需接口类型的引用。A typical way to enable a consumer is to declare a private field to contain a reference to the desired interface type.

  2. 标识回调方法。Identify a callback method. 必须将使用者中的方法标识为回调方法, 以便与提供程序建立连接。A method in the consumer must be identified as the callback method to establish a connection with the provider. 此方法检索提供程序实现的接口实例, 并将其分配给 (例如) 在第一步中创建的私有字段。This method retrieves an instance of the interface that the provider implements, and assigns it to (for example) the private field created in the first step. 用于标识使用者中的回调方法的 Web 部件方法是将ConnectionConsumer元数据属性 ( ConnectionConsumerAttribute由类定义) 添加到接收接口实例的方法。The Web Parts approach for identifying a callback method in the consumer is to add a ConnectionConsumer metadata attribute (defined by the ConnectionConsumerAttribute class) to the method that receives the interface instance. 添加属性后, 唯一必需的参数是用于使用者连接点的显示名称。When the attribute is added, the only required parameter is a display name to use for the consumer connection point. 还可以添加可选参数, 例如 ID。Optional parameters can also be added, such as an ID.

  3. 处理并输出接口实例中的数据。Process and output the data from the interface instance. 根据需要对数据执行任何内部处理, 通常使用者控件会将数据呈现到页面。Perform any internal processing as needed on the data, and then typically a consumer control will render the data to the page. 执行此操作的常见方法是重写控件的OnPreRender方法。A common way of doing this is to override the control's OnPreRender method.

    备注

    在同步请求期间, 使用者应在PreRender事件之后或之后立即直接从提供程序请求数据。During a synchronous request, a consumer should request data directly from the provider during or immediately after the PreRender event. 在异步请求期间, 如果在呈现过程中没有调用提供程序的回调方法, 开发人员可以假定未向使用者发送任何数据。During an asynchronous request, if the provider's callback method is not called at any point during rendering, the developer can assume that no data was sent to the consumer.

将控件作为使用者提供后, 控件可以参与连接 (假定提供程序控件也已配备并且可用)。After a control has been equipped to act as a consumer, the control can participate in connections (assuming that a provider control is also equipped and available). 若要在网页的标记中创建静态的声明性连接, 开发人员可以使用<asp:webpartconnection>元素。To create a static, declarative connection in the markup of a Web page, developers can use the <asp:webpartconnection> element. 如果用于ConnectionConsumer标识回调方法的使用者源代码中的属性指定了连接点的 ID, 则必须将该值分配给页面上的<asp:webpartconnection>元素ConsumerConnectionPointID中的属性。If the ConnectionConsumer attribute in the consumer source code that identifies the callback method specifies an ID for the connection point, then that value must be assigned to the ConsumerConnectionPointID attribute in the <asp:webpartconnection> element on a page. 如果使用者控件中定义了多个连接点, 开发人员可能为使用者连接点指定 ID 的原因。A reason that a developer might specify an ID for a consumer connection point is if there are multiple connection points defined in the consumer control. 如果没有为使用者控件中的使用者连接点指定 ID, 则无需将值分配给页中的ConsumerConnectionPointID属性, 因为将使用从获取的DefaultID默认值创建连接。定义域.If an ID is not specified for the consumer connection point in the consumer control, a value does not have to be assigned to the ConsumerConnectionPointID attribute in the page either, because the connection will be created using a default value obtained from the DefaultID field.

若要在代码中创建连接, 开发人员必须通过ConsumerConnectionPoint GetConsumerConnectionPoints调用方法并向其传递使用者控件的 id 或使用者控件中定义ConsumerConnectionPoint的对象的 id 或索引, 来创建一个新的对象。To create a connection in code, developers must create a new ConsumerConnectionPoint object by calling the GetConsumerConnectionPoints method and passing to it the ID of the consumer control, along with the ID or index of the defined ConsumerConnectionPoint object in the consumer control. 返回ConsumerConnectionPoint的对象以及对使用者控件的引用、对提供程序控件的引用以及对应ProviderConnectionPoint的对象ConnectWebParts都将传递给方法以创建新WebPartConnection的对象。The returned ConsumerConnectionPoint object, along with a reference to the consumer control, a reference to the provider control, and a corresponding ProviderConnectionPoint object, are all passed to the ConnectWebParts method to create a new WebPartConnection object.

尽管开发人员可以使用使用者连接点作为以声明方式或以编程方式建立连接的一部分, 但用户也可以与使用者连接点进行交互以通过用户界面 (UI) 建立连接。Although developers can use consumer connection points as part of establishing connections either declaratively or programmatically, users can also interact with consumer connection points to establish connections through the user interface (UI). 如果开发人员在ConnectionsZone网页上声明了一个控件, 则该控件将提供运行时 UI, 使用户能够创建连接。If developers declare a ConnectionsZone control on a Web page, it provides a run-time UI for users to create connections. 如果用户选择提供程序控件作为建立连接的起点, 只需要单击其连接谓词 (他们也可以选择使用者; 生成的连接没有差别), 则 UI 中将显示一个下拉列表控件, 其中包含提供程序可以将数据发送到的可用使用者连接点的显示名称 (如果有多个连接点, 则为多个点)。If users choose the provider control as the starting point for establishing the connection by clicking its connect verb (they could also choose the consumer; there is no difference in the resulting connection), in the UI they will see a drop-down list control with the display names of the available consumer connection point (or points if there are multiple ones) that the provider can send the data to. 用户必须选择一个使用者连接点以建立连接。Users must select a consumer connection point to establish a connection.

对象直接与特定使用者控件关联, 并将有关连接的详细信息存储在它从基类ConnectionPoint继承的属性中。 ConsumerConnectionPointA ConsumerConnectionPoint object associates directly with a specific consumer control, and stores details about a connection in the properties it inherits from the base ConnectionPoint class. 例如, 在继承InterfaceType的属性中, 使用者连接点保留其所使用的接口类型。For example, in the inherited InterfaceType property, a consumer connection point keeps the type of interface it uses. 如果连接中的提供者和使用者都理解接口类型, 则这些控件是兼容的, 并且能够形成直接连接。If the provider and consumer in a connection both understand the interface type, the controls are compatible and capable of forming a direct connection. 如果提供程序和使用者无法使用同一接口类型, 则它们是不兼容的, 并且WebPartTransformer必须使用对象将提供程序连接点InterfaceType的属性转换为使用者可以使用的类型。If the provider and consumer cannot work with the same interface type, they are incompatible and must use a WebPartTransformer object to translate the provider connection point's InterfaceType property into a type that the consumer can work with. 另一个重要的DisplayName继承属性是属性, 它提供在用户界面中显示的友好名称, 用户可以在创建连接时选择使用者连接点。Another important inherited property is the DisplayName property, which provides a friendly name to display in the UI for users to choose a consumer connection point when creating connections. 当开发人员将ConnectionConsumer属性添加到使用者控件中的回调方法时, 显示名称是必需的参数。The display name is the required parameter when developers add a ConnectionConsumer attribute to the callback method in a consumer control. 正如ID上面所述, 继承的属性也很有用, 因为当使用者具有多个连接点时, 它为使用者连接点提供唯一标识符。The inherited ID property is also useful, as indicated above, because it provides a unique identifier for a consumer connection point in the event that a consumer has multiple connection points. 使用者可以在其中ConsumerConnectionPoint定义多个对象, 在这种情况下, 当开发人员ConnectionConsumer将属性添加到方法时, 它们应该指定一个 ID 值以区分每个连接点。A consumer can have multiple ConsumerConnectionPoint objects defined in it, and in this case, when developers add the ConnectionConsumer attribute to a method, they should specify an ID value to distinguish each connection point. 另一个值得注意的AllowsMultipleConnections继承属性是属性, 该属性指示使用者连接点是否可以同时连接到多个提供程序。One other notable inherited property is the AllowsMultipleConnections property, which indicates whether a consumer connection point can connect simultaneously to multiple providers. 默认false情况下, 使用者连接点的此属性值为 ( true对于提供程序连接点为默认值)。This property value is false by default for consumer connection points (whereas it defaults to true for provider connection points).

类将几个唯一方法添加到它ConnectionPoint从类继承的成员。 ConsumerConnectionPointThe ConsumerConnectionPoint class adds several unique methods to the members it inherits from the ConnectionPoint class. SetObject方法调用使用者自己定义的回调方法从提供程序中检索接口实例。The SetObject method invokes the consumer's own defined callback method to retrieve the interface instance from the provider. SupportsConnection方法返回一个布尔值, 该值指示连接点能否根据关联的使用者控件的当前状态建立连接。The SupportsConnection method returns a Boolean value that indicates whether the connection point is able to establish connections, based on the current state of the associated consumer control.

构造函数

ConsumerConnectionPoint(MethodInfo, Type, Type, String, String, Boolean)

初始化 ConsumerConnectionPoint 类的新实例。Initializes a new instance of the ConsumerConnectionPoint class.

属性

AllowsMultipleConnections

获取一个指示连接点是否支持多个并发连接的值。Gets a value that indicates whether a connection point supports multiple simultaneous connections.

(继承自 ConnectionPoint)
ControlType

获取连接点与之关联的服务器控件的 TypeGets the Type of the server control with which a connection point is associated.

(继承自 ConnectionPoint)
DisplayName

获取一个字符串,该字符串用作在用户界面 (UI) 中表示连接点的友好显示名称。Gets a string that serves as a friendly display name to represent a connection point in the user interface (UI).

(继承自 ConnectionPoint)
ID

获取包含连接点的标识符的字符串。Gets a string that contains the identifier for a connection point.

(继承自 ConnectionPoint)
InterfaceType

获取连接点所使用的接口的类型。Gets the type of the interface used by a connection point.

(继承自 ConnectionPoint)

方法

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnabled(Control)

返回一个指示连接点是否可以参与连接的值。Returns a value that indicates whether a connection point can participate in connections.

(继承自 ConnectionPoint)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SetObject(Control, Object)

调用使用者控件中的回调方法,并从提供者控件检索接口实例。Invokes the callback method in a consumer control and retrieves the interface instance from a provider control.

SupportsConnection(Control, ConnectionInterfaceCollection)

确定使用者连接点当前能否建立连接。Determines whether a consumer connection point is currently capable of establishing a connection.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅