IWebPartField 接口

定义

定义使用单个字段数据连接两个服务器控件的提供者接口。

public interface class IWebPartField
public interface IWebPartField
type IWebPartField = interface
Public Interface IWebPartField
派生

示例

下面的代码示例演示如何使用 IWebPartField 接口在两个控件之间创建静态连接。 代码示例有三个部分:

  • 可以使用接口形成连接的两个自定义 WebPart 控件的 IWebPartField 源代码,其中一个控件充当提供程序,另一个控件充当使用者。

  • 承载控件并声明静态连接的网页(采用持久性格式)。

  • 说明示例代码运行时会发生什么情况。

代码示例的第一部分是两个自定义控件的源代码。 首先是实现接口的提供程序 IWebPartField 的代码。 为简单起见,提供程序会创建包含某些数据的表,而不是连接到数据库。 该方法 GetConnectionInterface 充当提供程序的连接点,即将接口实例返回到使用者的回调方法。 至于使用者,它将从名为 SetConnectionInterface 的提供程序中检索接口实例,该接口实例用属性 ConnectionConsumer 标记。 检索接口实例后,使用者在其方法中 OnPreRender 调用提供程序中方法的 GetFieldValue 实现以检索实际数据。

若要运行代码示例,必须编译此源代码。 可以显式编译它,并将生成的程序集放入网站的 Bin 文件夹或全局程序集缓存中。 或者,可以将源代码放在站点的App_Code文件夹中,该文件夹中将在运行时动态编译。 此代码示例使用动态编译。 有关演示如何编译的演练,请参阅 演练:开发和使用自定义 Web 服务器控件

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
  // This sample code creates a Web Parts control that acts as a provider 
  // of field data.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public sealed class FieldProviderWebPart : WebPart, IWebPartField
  {
    private DataTable _table;

    public FieldProviderWebPart() 
    {
        _table = new DataTable();

        DataColumn col = new DataColumn();
        col.DataType = typeof(string);
        col.ColumnName = "Name";
        _table.Columns.Add(col);

        col = new DataColumn();
        col.DataType = typeof(string);
        col.ColumnName = "Address";
        _table.Columns.Add(col);

        col = new DataColumn();
        col.DataType = typeof(int);
        col.ColumnName = "ZIP Code";
        _table.Columns.Add(col);

        DataRow row = _table.NewRow();
        row["Name"] = "John Q. Public";
        row["Address"] = "123 Main Street";
        row["ZIP Code"] = 98000;
        _table.Rows.Add(row);
    }

      [ConnectionProvider("FieldProvider")]
      public IWebPartField GetConnectionInterface()
    {
        return new FieldProviderWebPart();
    }

    public PropertyDescriptor Schema 
    {
        get 
        {
            /* The two parameters are row and field. Zero is the first record. 
                0,2 returns the zip code field value.   */ 
            return TypeDescriptor.GetProperties(_table.DefaultView[0])[2];
        }
    }

      void IWebPartField.GetFieldValue(FieldCallback callback) 
    {
        callback(Schema.GetValue(_table.DefaultView[0]));
    }
  } // end FieldProviderWebPart

  // This sample code creates a Web Parts control that acts as a consumer 
  // of an IWebPartField interface.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class FieldConsumerWebPart : WebPart
  {

    private IWebPartField _provider;
    private object _fieldValue;

    private void GetFieldValue(object fieldValue)
    {
      _fieldValue = fieldValue;
    }

    public bool ConnectionPointEnabled
    {
      get
      {
        object o = ViewState["ConnectionPointEnabled"];
        return (o != null) ? (bool)o : true;
      }
      set
      {
        ViewState["ConnectionPointEnabled"] = value;
      }
    }

    protected override void OnPreRender(EventArgs e)
    {
      if (_provider != null)
      {
        _provider.GetFieldValue(new FieldCallback(GetFieldValue));
      }
      base.OnPreRender(e);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {

      if (_provider != null)
      {
        PropertyDescriptor prop = _provider.Schema;

        if (prop != null && _fieldValue != null)
        {
          writer.Write(prop.DisplayName + ": " + _fieldValue);
        }
        else
        {
          writer.Write("No data");
        }
      }
      else
      {
        writer.Write("Not connected");
      }
    }

    [ConnectionConsumer("FieldConsumer", "Connpoint1", 
      typeof(FieldConsumerConnectionPoint), AllowsMultipleConnections = true)]
    public void SetConnectionInterface(IWebPartField provider)
    {
      _provider = provider;
    }

    public class FieldConsumerConnectionPoint : ConsumerConnectionPoint
    {
      public FieldConsumerConnectionPoint(MethodInfo callbackMethod, 
        Type interfaceType, Type controlType, string name, string id, 
        bool allowsMultipleConnections)
        : base(
        callbackMethod, interfaceType, controlType,
        name, id, allowsMultipleConnections)
      {
      }

      public override bool GetEnabled(Control control)
      {
        return ((FieldConsumerWebPart)control).ConnectionPointEnabled;
      }
    } // end FieldConsumerConnectionPoint
  } // end FieldConsumerWebPart
} // end namespace Samples.AspNet.CS.Controls
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  ' This sample code creates a Web Parts control that acts as a 
  ' provider of field data.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public NotInheritable Class FieldProviderWebPart
    Inherits WebPart
    Implements IWebPartField
    Private _table As DataTable


    Public Sub New()
      _table = New DataTable()

      Dim col As New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Name"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Address"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(Integer)
      col.ColumnName = "ZIP Code"
      _table.Columns.Add(col)

      Dim row As DataRow = _table.NewRow()
      row("Name") = "John Q. Public"
      row("Address") = "123 Main Street"
      row("ZIP Code") = 98000
      _table.Rows.Add(row)

    End Sub


    <ConnectionProvider("FieldProvider")> _
    Public Function GetConnectionInterface() As IWebPartField
      Return New FieldProviderWebPart()

    End Function


    Public ReadOnly Property Schema() As ComponentModel.PropertyDescriptor _
      Implements IWebPartField.Schema
      Get
        ' The two parameters are row and field. Zero is the first record. 
        ' 0,2 returns the zip code field value.   
        Return TypeDescriptor.GetProperties(_table.DefaultView(0))(2)
      End Get
    End Property


    Sub GetFieldValue(ByVal callback As FieldCallback) _
      Implements IWebPartField.GetFieldValue

      callback(Schema.GetValue(_table.DefaultView(0)))

    End Sub

  End Class


  ' This sample code creates a Web Parts control that acts as a 
  ' consumer of an IWebPartField interface.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class FieldConsumerWebPart
    Inherits WebPart

    Private _provider As IWebPartField
    Private _fieldValue As Object


    Private Sub GetFieldValue(ByVal fieldValue As Object)
      _fieldValue = fieldValue

    End Sub


    Public Property ConnectionPointEnabled() As Boolean
      Get
        Dim o As Object = ViewState("ConnectionPointEnabled")
        Return IIf(Not (o Is Nothing), CBool(o), True)
      End Get
      Set(ByVal value As Boolean)
        ViewState("ConnectionPointEnabled") = value
      End Set
    End Property


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      If Not (_provider Is Nothing) Then
        _provider.GetFieldValue(New FieldCallback(AddressOf GetFieldValue))
      End If
      MyBase.OnPreRender(e)

    End Sub


    Protected Overrides Sub RenderContents(ByVal writer As _
      HtmlTextWriter)

      If Not (_provider Is Nothing) Then
        Dim prop As PropertyDescriptor = _provider.Schema

        If Not (prop Is Nothing) AndAlso Not (_fieldValue Is Nothing) Then
          writer.Write(prop.DisplayName & ": " & _fieldValue)
        Else
          writer.Write("No data")
        End If
      Else
        writer.Write("Not connected")
      End If

    End Sub

    <ConnectionConsumer("FieldConsumer", "Connpoint1", _
      GetType(FieldConsumerConnectionPoint), AllowsMultipleConnections:=True)> _
    Public Sub SetConnectionInterface(ByVal provider As IWebPartField)
      _provider = provider

    End Sub

  End Class

  Public Class FieldConsumerConnectionPoint
    Inherits ConsumerConnectionPoint

    Public Sub New(ByVal callbackMethod As MethodInfo, _
      ByVal interfaceType As Type, ByVal controlType As Type, _
      ByVal name As String, ByVal id As String, _
      ByVal allowsMultipleConnections As Boolean)
      MyBase.New(callbackMethod, interfaceType, controlType, _
        name, id, allowsMultipleConnections)

    End Sub


    Public Overrides Function GetEnabled(ByVal control As Control) _
      As Boolean

      Return CType(control, FieldConsumerWebPart).ConnectionPointEnabled

    End Function

  End Class

End Namespace  ' Samples.AspNet.VB.Controls

代码示例的第二部分是声明静态连接并承载控件的网页。 页面顶部附近是一个 Register 指令,用于声明App_Code目录中包含的源代码的命名空间。 连接是使用 <asp:webpartconnection> 元素声明的。 自定义使用者和提供程序控件在元素内的<asp:webpartzone>元素中<zonetemplate>声明,因此必须能够连接 (它们必须驻留在继承自WebPartZoneBase类) 的区域中。

<%@ page language="C#" %>
<%@ Register tagprefix="IField" 
    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">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    
    </div>
    </form>
</body>
</html>
<%@ page language="VB" debug="true" %>
<%@ Register tagprefix="IField" 
    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">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>

在浏览器中加载页面。 使用者控件显示从指定字段提供的数据,提供程序通过接口的 IWebPartField 实例提供这些数据。

注解

此接口设计用于Web 部件连接。 在Web 部件连接中,驻留在区域中WebPartZoneBase的两个服务器控件建立连接并共享数据,一个控件充当使用者,另一个控件充当提供程序。 在Web 部件连接中共享数据的机制是接口实例,提供程序通过回调方法向使用者提供服务。 若要建立连接,使用者和提供程序必须同时使用同一接口类型来共享数据。 如果使用者无法识别提供程序发送的接口类型,则仍可以通过转换器 (对象) WebPartTransformer 将提供程序发送的接口实例转换为使用者识别的类型来连接控件。 有关连接的详细信息,请参阅WebPartConnectionWeb 部件连接概述

IWebPartField接口是一个提供程序接口,其中包含Web 部件控件集作为标准接口,用于基于数据字段创建连接。 还可以创建自定义接口以用于Web 部件连接,但在许多数据驱动的 Web 应用程序中,使用接口 (创建连接非常有用,请参阅IWebPartRow接口) 、表 (了解详细信息、查看IWebPartTable接口) 或数据源IWebPartField中的字段。 在典型的连接中, WebPart 充当提供程序的控件将实现 IWebPartField 接口,并在特殊回调方法中向使用者提供接口实例。 例如,提供程序可能实现 IWebPartField 用户信息表中包含 Web 用户的邮政编码数据的字段的接口。 另 WebPart 一个充当使用者的控件将定义用于接收接口实例的特殊方法,然后提取邮政编码数据,并基于邮政编码查找和显示天气信息。

接口 IWebPartField 有两个公开的成员。 该 Schema 属性返回有关对象中 PropertyDescriptor 封装的数据字段的架构信息。 该方法 GetFieldValue 声明实现者 (的方法,如提供程序控件) 在调用回调方法时检索接口实例的字段数据。

属性

Schema

获取用于在两个 WebPart 控件之间共享数据的数据字段的架构信息。

方法

GetFieldValue(FieldCallback)

返回字段的值,该字段由接口用作两个 WebPart 控件之间的连接基础。

适用于

另请参阅