WebPartConnection.ConsumerConnectionPointID WebPartConnection.ConsumerConnectionPointID WebPartConnection.ConsumerConnectionPointID WebPartConnection.ConsumerConnectionPointID Property

Определение

Получает или задает значение свойства для подключения, которое ссылается на идентификатор объекта, служащего в качестве точки подключения получателя для этого подключения.Gets or sets the property value on a connection that references the ID of the object serving as the consumer connection point for that connection.

public:
 property System::String ^ ConsumerConnectionPointID { System::String ^ get(); void set(System::String ^ value); };
public string ConsumerConnectionPointID { get; set; }
member this.ConsumerConnectionPointID : string with get, set
Public Property ConsumerConnectionPointID As String

Значение свойства

Строка, которая содержит идентификатор для точки подключения получателя.A string that contains the ID for the consumer connection point.

Примеры

В следующем примере кода показано декларативное и программное использование ConsumerConnectionPointID свойства.The following code example shows the declarative and programmatic use of the ConsumerConnectionPointID property.

Пример состоит из четырех частей:The example has four parts:

  • Пользовательский элемент управления, позволяющий изменять режим просмотра веб-части на странице.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. Дополнительные сведения о режимах вывода и описание исходного кода в этом элементе управления см. в разделе Пошаговое руководство. Изменение режима экрана на веб-части странице.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 the consumer and provider controls. Для выполнения примера кода необходимо скомпилировать этот исходный код.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. Пошаговое руководство, в котором демонстрируется компиляция , см. в разделе Пошаговое руководство. Разработка и использование пользовательского серверного веб-элемента управления.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.Xml;
  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. Обратите внимание, что соединение объявляется в разметке страницы <StaticConnections> с <asp:WebPartsConnection> помощью элементов и.Note that a connection is declared in the page markup, using the <StaticConnections> and <asp:WebPartsConnection> elements. Объявление соединения включает обязательный ConsumerConnectionPointID атрибут.The connection declaration includes the required ConsumerConnectionPointID attribute. Второй метод создания соединения отображается в Button1_Click методе, где код создает новое соединение, используя точку соединения, определенную в элементе управления потребителя.A second method for creating the connection appears in the Button1_Click method, where the code creates a new connection, using the connection point defined in the consumer control. Затем в Button2_Click методе код обращается к ConsumerConnectionPointID свойству.Then, in the Button2_Click method, the code accesses the ConsumerConnectionPointID property.

<%@ 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"];
    WebPartConnection conn1 = mgr.ConnectWebParts(zip1, provPoint,
      weather1, connPoint);
  }

  protected void Button2_Click(object sender, EventArgs e)
  {

    ConsumerConnectionPoint connpoint = 
      mgr.Connections[0].ConsumerConnectionPoint;
    
    lbl2.Text = "<h3>Consumer Connection Points Details</h3>" +
      "Display name: " + connpoint.DisplayName +
      "<br />" +
      "Connection Point ID: " + mgr.Connections[0].ConsumerConnectionPointID;

  }


  protected void mgr_DisplayModeChanged(object sender, WebPartDisplayModeEventArgs e)
  {
    if (mgr.DisplayMode == WebPartManager.ConnectDisplayMode)
    {
      Button1.Visible = true;
      Button2.Visible = true;
    }
    else
    {
      Button1.Visible = false;
      Button2.Visible = false;
    }

  }
</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" OnDisplayModeChanged="mgr_DisplayModeChanged">
        <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="Connect WebPart Controls" 
        OnClick="Button1_Click" 
        Visible="false" />
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="ConnectionPoint Details" 
        OnClick="Button2_Click" 
        Visible="false" /> 
      <br />   
      <asp:Label ID="lbl2" 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")
    mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint)

  End Sub

  Protected Sub Button2_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim connpoint As ConsumerConnectionPoint = _
      mgr.Connections(0).ConsumerConnectionPoint

    lbl2.Text = "<h3>Consumer Connection Points Details</h3>" & _
      "Display name: " & connpoint.DisplayName & _
      "<br />" & _
      "Connection Point ID: " & mgr.Connections(0).ConsumerConnectionPointID
  End Sub

  Protected Sub mgr_DisplayModeChanged (ByVal sender as Object, _
    ByVal e as WebPartDisplayModeEventArgs)

    If mgr.DisplayMode Is WebPartManager.ConnectDisplayMode Then
      Button1.Visible = True
      Button2.Visible = True
    Else
      Button1.Visible = False
      Button2.Visible = False
    End If

  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" OnDisplayModeChanged="mgr_DisplayModeChanged">
        <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="Connect WebPart Controls" 
        OnClick="Button1_Click" 
    Visible="false" />
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="ConnectionPoint Details" 
        OnClick="Button2_Click" 
        Visible="false" /> 
      <br />   
      <asp:Label ID="lbl2" runat="server" />
    </div>
    </form>
</body>
</html>

После загрузки страницы в браузере соединение уже существует из-за статического соединения, объявленного на странице.After you load the page in a browser, a connection already exists because of the static connection declared in the page. Введите некоторый текст в элемент управления поставщика и обратите внимание, что он отображается в потребителе из-за соединения.Enter some text in the provider control, and note that it is displayed in the consumer due to the connection. Затем отключите элементы управления.Next, disconnect the controls. С помощью раскрывающегося списка режим экрана переключите страницу в режим подключения.Using the Display Mode drop-down list control, switch the page to connect mode. Щелкните меню глаголы (представленное стрелкой вниз в заголовке окна) на одном из WebPart элементов управления и выберите команду Подключить.Click the verbs menu (represented by the downward arrow in the title bar) on one of the WebPart controls, and click the connect verb. Нажмите кнопку Disconnect (отключить ).Click the Disconnect button. Используйте кнопку подключить элементы управления WebPart , чтобы повторно создать соединение между двумя элементами управления.Use the Connect WebPart Controls button to recreate a connection between the two controls. Нажмите кнопку сведения о ConnectionPoint , чтобы запустить код, обращающийся к ConsumerConnectionPointID значению свойства.Click the ConnectionPoint Details button to run the code that accesses the ConsumerConnectionPointID property value. Значение записывается в метку под элементами управления.The value is written out in a label below the controls.

Комментарии

Для статического соединения, объявленного в разметке веб-страницы, разработчики могут указать, какая точка подключения получателя будет использоваться для соединения, назначив значение ConsumerConnectionPointID атрибуту <asp:webpartconnection> элемента.For a static connection declared in the markup of a Web page, developers can specify which consumer connection point will be used for the connection by assigning a value to the ConsumerConnectionPointID attribute on the <asp:webpartconnection> element. Если атрибуту не присвоено значение, DefaultID используется значение свойства.If a value is not assigned to the attribute, the DefaultID property value is used.

При создании динамических (программных) соединений обычно не следует задавать значение ConsumerConnectionPointID свойства.When you create dynamic (programmatic) connections, normally you should not set the value of the ConsumerConnectionPointID property. Можно просто вызвать ConnectWebParts метод WebPartManager для элемента управления, передав ему объекты точек подключения потребителя и потребителя (вместе с другими обязательными параметрами), и этот метод определяет правильный идентификатор, используемый для подключения потребителя. точки.You can simply call the ConnectWebParts method on the WebPartManager control, passing to it the consumer and consumer connection point objects (along with the other required parameters), and that method determines the correct ID to use for the consumer's connection point. Аналогично при отключении можно вызвать DisconnectWebParts метод без ConsumerConnectionPointID указания значения свойства.Similarly, when you disconnect, you can call the DisconnectWebParts method without needing to specify the ConsumerConnectionPointID property value.

Примечание

Идентификатор точки подключения потребителя можно определить при назначении WebPart или другого серверного элемента управления в качестве потребителя.The ID of a consumer's connection point can be determined when you designate a WebPart or other server control as a consumer. Необходимо указать метод в потребителе, который извлекает экземпляр интерфейса, предоставляемого либо элементом управления поставщика, либо преобразователем.You must identify a method in the consumer that retrieves an instance of an interface furnished by either a provider control or a transformer. Чтобы опознать метод, пометьте его ConnectionConsumer атрибутом Code.To identify the method, mark it with the ConnectionConsumer code attribute. При добавлении этого атрибута можно добавить необязательный параметр строкового значения, который служит идентификатором ConsumerConnectionPoint объекта потребителя.When you add this attribute, you can add an optional string value parameter that serves as an ID for the consumer's ConsumerConnectionPoint object. Если указать значение для необязательного параметра ID, это значение станет значением ConsumerConnectionPointID свойства для соединения.If you supply a value for the optional ID parameter, that value becomes the value of the ConsumerConnectionPointID property for the connection. Если значение идентификатора не указано, DefaultID используется значение свойства.If you do not supply an ID value, the DefaultID property value is used.

Применяется к

Дополнительно