Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

WebPartConnection Classe

Provides an object that enables two WebPart controls to form a connection. Essa classe não pode ser herdada.

Namespace:  System.Web.UI.WebControls.WebParts
Assembly:  System.Web (em System.Web. dll)

[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class WebPartConnection

In the Web Parts control set, a connection is a link or association between two WebPart (or other server or user) controls that enables them to share data.Essa capacidade de compartilhar dados permite que controles conectados para ser usado de maneiras que excedem a funcionalidade oferecida pelos controles isolados.Por exemplo, se um Controlarar fornece os dados do código postal e um outro Controlarar pode ler os dados e fornecer informações clima local baseia o código postal, em seguida, conectada a capacidade dos dois Controlarars fornece mais valor aos usuários.Para estender esse exemplo, outros Controlarars pôde ser criados que também Exibir informações com base em um Código postal, such as um Controlarar com links para local notícias e Tudo esses Controlarars que podem trabalho com dados Código postal pode compartilhar dados com o Simples Controlarar que fornece uma Código postal.End users of Web Parts applications can create and manage connections between all such compatible controls directly from a Web browser, using the standard connections user interface (UI) provided by the ConnectionsZone control, or using a custom UI provided by a developer.

This WebPartConnection class overview is a general statement of the basic details for creating a connection.For more on specific components and requirements involved in creating connections, see Visão Geral Sobre as Conexões do Web Parts, or see the reference classes and code examples mentioned in the following discussion.Há vários aspectos fundamentais de uma conexão da Web Parts:

  • Two WebPart controls.Cada conexão da Web Parts consiste de dois controles.É possível para um Controlarar para participar more than uma conexão simultaneamente, mas cada Simples conexão consiste exatamente dois Controlarars.The controls can derive directly from the WebPart base class, or they can be other server controls, including ASP.NET controls, custom server controls, and user controls.Controls that do not derive from the WebPart class, if placed in a WebPartZoneBase zone, are automatically wrapped with a GenericWebPart object at run time, which enables them to inherit from the WebPart class and function as run-time WebPart controls.

  • Controls residing in WebPartZoneBase zones.Both WebPart controls and any other type of server control must reside in a WebPartZoneBase zone to be able to participate in Web Parts connections (and most other Web Parts features).

  • Os consumidores e provedores.Em cada conexão da Web Parts há dois controles: Um provedor de dados e um consumidor de dados.O provedor fornece dados para o consumidor por meio de um método de retorno de chamada especificado que retorna dados em Formulárioulário de uma interface.(Para obter um exemplo de como criar e especificar o método de retorno de chamada, consulte a seção exemplo deste tópico.) Esse método de retorno de chamada é conhecido como um ponto de conexão do provedor.The details of this connection point (its "friendly" name, an ID, and the type of the returned interface) are contained in a ProviderConnectionPoint object associated with the provider control.O consumidor recebe os dados por meio de um método especificado que pode aceitar uma instância da interface.This method is known as a consumer connection point, and the details of the connection point (name, ID, and type of interface) are contained in a ConsumerConnectionPoint object associated with the consumer control.

  • Controles compatíveis ou um transformador válido.For a connection to work, the consumer and provider must either be compatible (meaning that their specified connection point methods can work with the same type of interface), or there must be a WebPartTransformer object capable of translating the type offered by the provider into a type understood by the consumer.

  • A WebPartConnection object.For a connection to exist, there must be an instance of the WebPartConnection class that contains references to the provider and consumer controls, along with the details of their connection points.If the provider and consumer are incompatible and instead use a WebPartTransformer object to connect, the connection references the transformer.

  • Um meio de estabelecer a conexão.After compatible consumer and provider controls have been properly designed with connection point methods and placed in a zone, and a WebPartConnection object is available, the last basic step necessary is to initiate the connection.Uma maneira que isso pode acontecer é para usuários criar a conexão por meio de interface do usuário.If you place an <asp:connectionszone> element on the page, and the other required components for a connection are in place, at run time a user can switch the page into connect display mode, click a connect verb on the verbs menu of either the provider or consumer, and a connection UI (based on the ConnectionsZone control) will appear.A esta interface de usuário, o usuário pode iniciar a conexão.Outra maneira para iniciar a conexão é fazê-lo por meio de programação.Em maiúscminúsc, através de interface do usuário ou programaticamente, o subjacente é o mesmo método que inicia a conexão.The application calls the ConnectWebParts method (or the ConnectWebParts method if using a transformer) on the WebPartManager control, passing to it the provider, the consumer, and their respective connection point objects, and the method returns a WebPartConnection object.

The WebPartConnection class defines an object that encapsulates the essential details of a connection between two WebPart controls.A classe consiste em quase inteiramente de propriedades relacionadas aos detalhes de uma determinada conexão.Várias propriedades interessam Controlarar do consumidor em uma conexão.The Consumer property references the consumer control itself, and the ConsumerID property references the consumer's ID.The ConsumerConnectionPoint object, which contains the details of the consumer's connection point, is referenced by the consumer's ConsumerConnectionPoint property.The ConsumerConnectionPointID property references the ID of the ConsumerConnectionPoint object.Tudo Esses consumidor-relacionado propriedades conexão devem ter um valor atribuído a eles para criar uma conexão.

The WebPartConnection class also has several properties that relate to the provider control in a connection, and these correspond to the properties for a consumer.The Provider property references the provider control itself, while the ProviderID property references its ID.The ProviderConnectionPoint property references the ProviderConnectionPoint object, and the ProviderConnectionPointID property references the ID of the provider's connection point.

Várias propriedades interessam o estado da conexão.The IsActive property indicates whether the connection is active (currently exchanging data) or inactive (still connected but not actively sharing data).The IsShared property indicates whether the connection is a shared (available to all users of a page) or a user-specific connection, and the IsStatic property indicates whether the control is static (declared in the page markup and thus permanent) or dynamic (created programmatically, meaning that it can be deleted).

The following code example demonstrates how to create a simple connection between two WebPart controls.O exemplo mostra três maneiras de formação de uma conexão: declaratively, by placing tags for the connection in the markup of the Web page; programmatically, by creating the connection in code; and through the UI, by placing a ConnectionsZone control on the page, which enables users to establish a connection.

O exemplo de código possui quatro partes:

  • Um Controlarar de Usuário que permite que você Alterar o modo de Exibir Web Parts em uma página.

  • Source code for an interface and two WebPart controls acting as the provider and the consumer for a connection.

  • Uma página da Web para Host Tudo controles e executar o exemplo de código.

  • Uma explicação de como executar a página exemplo.

O Primeiro parte este exemplo de código é o Controlare usuário que permite aos usuários modos exibir alteração em um página da Web.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 Passo-a-Passo: Changing Exibir Modes on a Page Web Parts.

<%@ control language= classname=%>
<script runat=>

 
  WebPartManager _manager;

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

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

    String browseModeName = WebPartManager.BrowseDisplayMode.Name;

    
     (WebPartDisplayMode mode  _manager.SupportedDisplayModes)
    {
      String modeName = mode.Name;
      
       (mode.IsEnabled(_manager))
      {
        ListItem item =  ListItem(modeName, modeName);
        DisplayModeDropdown.Items.Add(item);
      }
    }

    
    
     (_manager.Personalization.CanEnterSharedScope)
    {
      Panel2.Visible = ;
       (_manager.Personalization.Scope == PersonalizationScope.User)
        RadioButton1.Checked = ;
      
        RadioButton2.Checked = ;
    }

  }

  
   DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e)
  {
    String selectedMode = DisplayModeDropdown.SelectedValue;

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

  
   Page_PreRender(object sender, EventArgs e)
  {
    ListItemCollection items = DisplayModeDropdown.Items;
     selectedIndex = 
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
    DisplayModeDropdown.SelectedIndex = selectedIndex;
  }

  
    LinkButton1_Click(object sender, EventArgs e)
  {
    _manager.Personalization.ResetPersonalizationState();
  }

  
    RadioButton1_CheckedChanged(object sender, EventArgs e)
  {
     (_manager.Personalization.Scope == PersonalizationScope.Shared)
      _manager.Personalization.ToggleScope();
  }

  
    RadioButton2_CheckedChanged(object sender, EventArgs e)
  {
     (_manager.Personalization.CanEnterSharedScope && 
        _manager.Personalization.Scope == PersonalizationScope.User)
      _manager.Personalization.ToggleScope();
  }
</script>
<div>
  <asp:Panel ID= runat= 
    Borderwidth= 
    Width= 
    BackColor=
    Font-Names= >
    <asp:Label ID= runat= 
      Text= 
      Font-Bold=
      Font-Size=
      Width= 
      AssociatedControlID=/>
    <asp:DropDownList ID= runat=  
      AutoPostBack= 
      Width=
      OnSelectedIndexChanged= />
    <asp:LinkButton ID= runat=
      Text= 
      ToolTip=
      Font-Size= 
      OnClick= />
    <asp:Panel ID= runat= 
      GroupingText=
      Font-Bold=
      Font-Size= 
      Visible= >
      <asp:RadioButton ID= runat= 
        Text= 
        AutoPostBack=
        GroupName= OnCheckedChanged= />
      <asp:RadioButton ID= runat= 
        Text= 
        AutoPostBack=
        GroupName= 
        OnCheckedChanged= />
    </asp:Panel>
  </asp:Panel>
</div>


O segundo parte o exemplo de código é a codificar origem para a interface e controles.The source file contains a simple interface named IZipCode.There is also a WebPart class named ZipCodeWebPart that implements the interface and acts as the provider control.Its ProvideIZipCode method is the callback method that implements the interface's only member.O método simplesmente retorna uma instância da interface.Note that the method is marked with a ConnectionProvider attribute in its metadata.Este é o mecanismo para identificar o método como o método de retorno de chamada para ponto de conexão do provedor.The other WebPart class is named WeatherWebPart, and it acts as the consumer for the connection.This class has a method named GetZipCode that gets an instance of the IZipCode interface from the provider control.Note that this method is marked as the consumer's connection point method with a ConnectionConsumer attribute in its metadata.

Para o exemplo de código a ser executado, você deve compilar este código-fonte.Você pode compilá-lo explicitamente e colocar o assembly resultante na pasta Bin do seu site da Web ou o cache global de assemblies.Como alternativa, você pode colocar o código-fonte em seu site na pasta App_Code, onde ele irá ser compilada em tempo de execução dinamicamente.Este exemplo de código usa compilação dinâmica.For a walkthrough that demonstrates how to compile, see Passo-a-Passo: Desenvolvendo e usando um Controlar Servidor Personalizar.

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

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

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

     ZipCodeWebPart()
    {
    }

    
    
    [Personalizable()]
      string ZipCode
    {
       {  zipCodeText; }
       { zipCodeText = value; }
    }

    
    [ConnectionProvider(, )]
     IZipCode ProvideIZipCode()
    {
       ;
    }

       CreateChildControls()
    {
      Controls.Clear();
      input =  TextBox();
      .Controls.Add(input);
      send =  Button();
      send.Text = ;
      send.Click +=  EventHandler(.submit_Click);
      .Controls.Add(send);
    }

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

  }

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

    
    
    
    [ConnectionConsumer(, )]
      GetIZipCode(IZipCode Provider)
    {
      _provider = Provider;
    }

       OnPreRender(EventArgs e)
    {
      EnsureChildControls();

       (._provider != )
      {
        _zipSearch = _provider.ZipCode.Trim();
        DisplayContent.Text =  + _zipSearch;
      }
    }

       CreateChildControls()
    {
      Controls.Clear();
      DisplayContent =  Label();
      .Controls.Add(DisplayContent);
    }

  }
}


A terceira parte do exemplo de código é a página da Web.Near the top are the Register directives for the user control and the custom WebPart controls.Because the example assumes dynamic compilation of the controls, the source code for the controls should be in an App_Code subfolder; the Register tag in the page references only an arbitrary tag prefix and the namespace of the controls.The custom WebPart controls (the provider and consumer) are declared within the Web page's <asp:webpartzone> element, inside a <zonetemplate> element.

A página fornece três maneiras para Formulárioulárior uma conexão entre os controles Personalizars.O primeiro método é declarativo.In the markup for the page, a <StaticConnections> element is declared, and within that is an <asp:WebPartConnections> element, with the various consumer and provider details of the connection specified as attributes.This is one way to create a connection, by declaring it directly in the Web page, specifically within the <asp:WebPartManager> element.Devido a isso Estático conexão, uma conexão entre o Personalizar dois controles é criado imediatamente o tempo primeiro carrega a página.

A second method for forming a connection between the controls is provided by the <asp:connectionszone> element in the page.If a user switches a page into connect display mode at run time, and clicks a connect verb on one of the custom controls, the <asp:connectionszone> element automatically renders the UI for creating a connection.

A página também demonstra uma maneira de criar uma conexão, que é a fazê-lo programaticamente terceira.In the Button1_Click method, the code creates a ProviderConnectionPoint object for the provider control, and retrieves its connection point details by calling the GetProviderConnectionPoints method.It carries out a similar task for the consumer control, calling the GetConsumerConnectionPoints method.Finally, it creates the new WebPartConnection object by calling the ConnectWebParts method on the WebPartManager control.

<%@ Page Language= %>
<%@ Register TagPrefix= 
    TagName=
    Src= %>
<%@ Register TagPrefix= 
    Namespace= %>

<!DOCTYPE html PUBLIC "-
    "http:
<script runat=>

    Button1_Click(object sender, EventArgs e)
  {
    ProviderConnectionPoint provPoint = 
      mgr.GetProviderConnectionPoints(zip1)[];
    ConsumerConnectionPoint connPoint = 
      mgr.GetConsumerConnectionPoints(weather1)[];
    WebPartConnection conn1 = mgr.ConnectWebParts(zip1, provPoint,
      weather1, connPoint);
  }

    mgr_DisplayModeChanged(object sender, 
    WebPartDisplayModeEventArgs e)
  {
     (mgr.DisplayMode == WebPartManager.ConnectDisplayMode)
      Button1.Visible = ;
    
      Button1.Visible = ;
  }
</script>

<html xmlns="http:
<head runat=>
    <title>Untitled Page</title>
</head>
<body>
    <form id= runat=>
    <div>
      <asp:WebPartManager ID= runat= 
    OnDisplayModeChanged=>
        <StaticConnections>
          <asp:WebPartConnection ID=
            ConsumerConnectionPointID=
            ConsumerID=
            ProviderConnectionPointID=
            ProviderID= />
        </StaticConnections>
      </asp:WebPartManager>
      <uc1:DisplayModeMenuCS ID= runat= />
      <asp:WebPartZone ID= runat=>
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID= runat=
            Title= />
          <aspSample:WeatherWebPart ID= runat= 
            Title= />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID= runat=>
      </asp:ConnectionsZone>
      <asp:Button ID= runat= 
        Text= 
        OnClick= 
    Visible= />
    </div>
    </form>
</body>
</html>


After you load the Web page in a browser, the first connection already exists because it is declared within the <StaticConnections> element.Enter some text in the ZIP Code Provider control, and it will be displayed in the consumer control.Avançar, Disconnect the two Controls.Using the Display Mode drop-down list control, change the page to connect display mode.Click the verbs menu (represented by a downward arrow in the title bar) for each of the WebPart controls, and notice that each has a Connect option.Este é um Conectar verbo, que aparece no menu de verbos somente quando a página estiver no Conectar modo.Click the connect verb on one of the controls, and the connection UI provided by the ConnectionsZone control appears.Click the Disconnect button to end the static connection between the controls.Use the Display Mode control to return the page to browse mode.Tentar inserir um novo texto no provedor novamente, e Anotação que porque os Controlarars são desconectados, o texto falha Atualizar no Controlarar de consumidor.

Avançar, use o mesmo método como acima para Switch a página em modo de Exibir conectar novamente.Clique em um Conectar verbo em um dos controles.Click the Create a Connection link, and use the UI provided by the ConnectionsZone control to create a connection between the controls.Esse é o segundo método para criar uma conexão.Anotação que assim a conexão é formado, o último Cadeia de Caracteres você inseriu no Controlarar de provedor (que falha apareça porque os Controlarars foram desconectados) aparece de repente no consumidor, porque a conexão tiver sido recriado.Click the Disconnect button to end the current connection that you just created.Retorna a página para procurar o modo.Enter Some Novo Texto in the provedor to demonstrar that the Texto Is Not Updated, and that the Controls again are Disconnected.

Retorna a página para conectar-se o modo de Exibir.Instead of clicking a connect verb, click the Connect WebPart Controls button, which illustrates the third method of forming a connection.This approach connects the controls programmatically in one simple step without having to use the ConnectionsZone control.Anotação that as the conexão is created, the last Cadeia de Caracteres you entered in the provedor appears suddenly in the Controlarar consumidor.

  • AspNetHostingPermission 

    Para operando em um ambiente hospedado.Exigem valor: LinkDemand; Permission value: Minimal.

System.Object
  System.Web.UI.WebControls.WebParts.WebPartConnection

Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.
Mostrar: