IParametersInProvider 接口

请注意:此 API 现在已过时。

允许 Web 部件向其他使用者 Web 部件传达其参数列表的提供程序。

命名空间:  Microsoft.SharePoint.WebPartPages.Communication
程序集:  Microsoft.SharePoint(位于 Microsoft.SharePoint.dll 中)

语法

声明
<ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")> _
Public Interface IParametersInProvider
用法
Dim instance As IParametersInProvider
[ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")]
public interface IParametersInProvider

备注

需要传递的参数的常规集合的部件,应使用IParametersInProvider接口。它可在方案中需要提供程序部件动态更改基于初始化参数传递的使用者部件其用户界面。以下的初始化参数还可以指定哪些参数所需从提供程序。

IParametersInProvider只能连接到IParametersInConsumer接口。连接到IParametersInConsumer接口的IParametersInProvider接口是直接连接,因此,就显示没有转换器对话框。若要正确使用传递的值,使用部件可能需要与服务提供商发送的数据了解设计。

示例

下面的代码示例显示简单服务器端IParametersInProvider Web 部件。它可以连接到服务器实现IParametersInConsumer接口的其他 Web 部件。动态,本示例显示一系列基于初始化参数提供的使用者 Web 部件的文本框。它还创建所需的参数的验证控件。连接到IParametersInConsumer示例 Web 部件时, 提供程序部件中显示的字体大小、 颜色、 粗细和家人的文本框。当提交表单时,此 Web 部件将参数传递给其他连接的 Web 部件 (如果已输入所需的字段的所有)。

特定于使其可连接的 Web 部件是 8 个步骤。以下步骤进行编号和注释在下面的示例代码。

' Common .NET required namespaces
Imports System
Imports System.ComponentModel
Imports System.Web.UI

' WebPart required namespaces
Imports Microsoft.SharePoint.WebPartPages
Imports System.Xml.Serialization
Imports System.Web.UI.WebControls

' Namespace required for ArrayLists
Imports System.Collections

' Code Access Security namespaces
Imports System.Security
Imports Microsoft.SharePoint.Utilities

' Step #1: Reference the Communication namespace.
Imports Microsoft.SharePoint.WebPartPages.Communication



Namespace ConnectionCodeSamples
   ' Step #2: Inherit from the WebPart base class and implement the 
   ' IParametersInProvider interface.
   
   Public Class ServerSideParametersInProvider
      Inherits WebPart
      Implements IParametersInProvider
      ' Step #3: Declare the IParametersInProvider Events
      ' Because this class implements the IParametersInProvider 
      ' interface, it must declare the interface members 
      ' ParametersInReady and NoParametersIn.  
      Public Event ParametersInReady As ParametersInReadyEventHandler Implements IParametersInProvider.ParametersInReady
      Public Event NoParametersIn As NoParametersInEventHandler Implements IParametersInProvider.NoParametersIn
      
      ' Declare variable for keeping track of the connection state.
      Private _connected As Boolean = False
      Private _connectedWebPartTitle As String = String.Empty
      Private _registrationErrorMsg As String = "An error has occurred trying to register your connection interfaces."
      Private _registrationErrorOccurred As Boolean = False
      Private _notConnectedMsg As String = "NOT CONNECTED. To use this Web Part connect it to a ParametersIn Consumer Web Part."
      
      ' Declare variables for Web Part user interface.
      Private _connectedWebPartLabel As String = "Connected to Web Part"
      Private _parametersReadyButton As Button
      Private _parametersReadyButtonClicked As Boolean = False
      Private _noParametersInButton As Button
      Private _noParametersInButtonClicked As Boolean = False
      Private _fontAttributeTextBox() As TextBox
      Private _fieldListKey As String = "ProviderFieldList" 'Key for ViewState StateBag
      Private _requiredFieldsKey As String = "RequiredFields" 'Key for ViewState StateBag
      Private _requiredFieldText As String = "Required Field"
      Private _requiredInputNotice As String = "*Required input"
      
      ' Declare variables for Text Box information.
      Private _fieldList() As String
      Private _fieldDisplayList() As String
      Private _requiredFieldFlag() As Boolean
      
      
      ' Step #4: Override the EnsureInterfaces method and call 
      ' RegisterInterface method.
      ' The EnsureInterfaces method is called by the Web Part 
      ' infrastructure during the ASP.NET PreRender event 
      ' and allows the part to register all of its connection 
      ' interfaces.
      Public Overrides Sub EnsureInterfaces()
         ' If your Web Part is installed in the bin directory and the 
         ' Code Access Security (CAS) setting doesn't 
         ' allow Web Part Connections, an exception will be thrown. 
         ' To allow your Web Part to behave 
         ' well and continue working, a try/catch block should be used 
         ' when attempting to register interfaces.
         ' Web Part Connections will only work if the level attribute 
         ' of the <trust> tag in the web.config file is set to 
         ' WSS_Minimal, WSS_Medium, or Full. By default a new 
         ' SharePoint site is installed with the trust level set to 
         ' WSS_Minimal.  
         Try
            ' Register the IParametersInProvider interface.
            ' <param name="interfaceName">Friendly name of the 
            ' interface that is being implemented.</param>
            ' <param name="interfaceType">Specifies which interface is 
            ' being implemented.</param>
            ' <param name="maxConnections">Defines how many times this 
            ' interface can be connected.</param>
            ' <param name="runAtOptions">Determines where the interface 
            ' can run.</param>
            ' <param name="interfaceObject">Reference to the object 
            ' that is implementing this interface.</param>
            ' <param name="interfaceClientReference">Name used to 
            ' reference the interface on the client.  
            ' This is a server side example so the value is set to 
            ' empty string.</param>
            ' <param name="menuLabel">Label for the interface that 
            ' appears in the UI</param>
            ' <param name="description">Description of the interface 
            ' that appears in the UI</param>
            ' <param name="allowCrossPageConnection">Specifies if the 
            ' interface can connect to a Web Part
            ' on a different page.  This is an optional parameter with 
            ' a default of false. Note that only some 
            ' server side interfaces are allowed to go cross page by 
            ' the Web Part Infrastructure. 
            ' The IParametersInProvider interface is allowed to go 
            ' cross page.</param>
            RegisterInterface("MyParametersInProviderInterface", InterfaceTypes.IParametersInProvider, WebPart.LimitOneConnection, ConnectionRunAt.Server, Me, "", "Provide Parameters To", "Provides a font parameters to a consumer Web Part.", True) 'InterfaceName    
         'InterfaceType
         'MaxConnections
         'RunAtOptions
         'InterfaceObject
         'InterfaceClientReference
         'MenuLabel
         'Description
         'allowCrossPageConnection
         Catch se As SecurityException
            _registrationErrorOccurred = True
         End Try
      End Sub 'EnsureInterfaces
      
      
      
      ' Step #5: Override the CanRunAt method.
      ' The CanRunAt method is called by the Web Part infrastructure 
      ' during the ASP.NET PreRender event
      ' to determine where the Web Part can run based on its current 
      ' configuration.
      Public Overrides Function CanRunAt() As ConnectionRunAt
         'This Web Part can run on the server
         Return ConnectionRunAt.Server
      End Function 'CanRunAt
      
      
      ' Step #6: Override the PartCommunicationConnect method.
      ' The PartCommunicationConnect method is called by the Web Part 
      ' infrastructure to notify the Web Part that it
      ' is connected during the ASP.NET PreRender event. Relevant 
      ' information is passed to the part such as 
      ' the interface it is connected over, the Web Part it is being 
      ' connected to, and where the part will be running, 
      ' either client or server side. 
      ' <param name="interfaceName">Friendly name of the interface that 
      ' is being connected</param>
      ' <param name="connectedPart">Reference to the other Web Part 
      ' that is being connected to</param>
      ' <param name="connectedInterfaceName">Friendly name of the 
      ' interface on the other Web Part</param>
      ' <param name="runAt">Where the interface should execute</param>
      Public Overrides Sub PartCommunicationConnect(interfaceName As String, connectedPart As WebPart, connectedInterfaceName As String, runAt As ConnectionRunAt)
         'Keep track of whether connected or not
         If interfaceName = "MyParametersInProviderInterface" Then
            'Keep track of the Connection
            _connected = True
            _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
         End If
      End Sub 'PartCommunicationConnect
      
      ' Step #7: Implement the PartCommunicationMain() method.
      ' The PartCommunicationMain method is called by the Web Part 
      ' infrastructure on the client during the ASP.NET PreRender
      ' event to allow the part to pass its primary data to the other connected parts.
      ' It is important to always fire either the ParametersInReady or the NoParametersIn event. Some parts
      ' may not behave properly if they are left waiting for this information.
      ' ParametersInReady should be fired to send the parameters.
      ' NoParametersIn should be fired to indicate that there is no 
      ' change in the parameters.
      Public Overrides Sub PartCommunicationMain()
            ' Ensure that all of the Web Part's controls are created.
            EnsureChildControls()

            'Check if connected
            If _connected Then
                ' Create the ParametersInReadyEventArgs object for the ParametersInReady event.
                Dim parametersInReadyEventArgs As New ParametersInReadyEventArgs()

                If _parametersReadyButtonClicked Then 'ParametersInReady Button was clicked

                    ' Set the parameter values to the text box values.
                    If Not (_fieldList Is Nothing) Then
                        parametersInReadyEventArgs.ParameterValues = New String(_fieldList.Length) {}

                        Dim index As Integer
                        For index = 0 To _fieldList.Length - 1
                            parametersInReadyEventArgs.ParameterValues(index) = _fontAttributeTextBox(index).Text
                        Next index

                        ' Fire the ParametersInReady event.
                        RaiseEvent ParametersInReady(Me, parametersInReadyEventArgs)
                        '_fieldList is null
                    Else
                        ' Fire the event.
                        RaiseEvent NoParametersIn(Me, New EventArgs())
                    End If
                    _parametersReadyButtonClicked = False
                ElseIf _noParametersInButtonClicked Then 'NoParametersIn Button was clicked                       
                    ' Fire the NoParametersIn event.
                    RaiseEvent NoParametersIn(Me, New EventArgs())
                    _noParametersInButtonClicked = False
                End If
            End If
        End Sub
      
      ' Step #8: Implement the ParametersInConsumerInit event handler.
      ' The connected consumer part will call this method during its 
      ' PartCommunicationInit phase
      ' to pass initialization information to the provider Web Part. 
      ' The parameters names from the
      ' consumer Web Part are passed in. In this example, these values 
      ' are used to dynamically 
      ' generate the input text boxes in the provider Web Part.
      ' <param name="sender">Consumer Web Part</param>
      ' <param name="parametersInConsumerInitEventArgs">The args passed 
      ' by the Consumer</param>
      Public Sub ParametersInConsumerInit(sender As Object, parametersInConsumerInitEventArgs As ParametersInConsumerInitEventArgs) _
             Implements IParametersInProvider.ParametersInConsumerInit
         ' Initialize field lists.
         Dim paramProps As ParameterInProperty() = parametersInConsumerInitEventArgs.ParameterInProperties
         
         If Not (paramProps Is Nothing) Then
            _fieldList = New String(paramProps.Length-1) {}
            _fieldDisplayList = New String(paramProps.Length-1) {}
            _requiredFieldFlag = New Boolean(paramProps.Length)-1 {}
            
            ' Populate field lists.
            Dim index As Integer
            For index = 0 To paramProps.Length - 1
               _fieldList(index) = paramProps(index).ParameterName
               _fieldDisplayList(index) = paramProps(index).ParameterDisplayName
               _requiredFieldFlag(index) = paramProps(index).Required
            Next index
         End If
      End Sub 'ParametersInConsumerInit
      
      
      Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
         ' Check for connection interface registration error.
         If _registrationErrorOccurred Then
            output.Write(_registrationErrorMsg)
            Return
         End If
         
         ' Check if connected.
         If _connected Then
            ' Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Generate input textboxes.
            Dim fieldName As String
            output.RenderBeginTag(HtmlTextWriterTag.Table)
            Dim vIndex As Integer = 0 'Validation control index
            Dim index As Integer
            For index = 0 To _fieldDisplayList.Length - 1
               fieldName = _fieldDisplayList(index)
               
               output.RenderBeginTag(HtmlTextWriterTag.Tr)
               output.RenderBeginTag(HtmlTextWriterTag.Td)
               output.RenderBeginTag(HtmlTextWriterTag.B)
               
               ' Insert asterisk for required fields.
               If _requiredFieldFlag(index) Then
                  output.Write("<font color=red>*</font>")
               Else
                  output.Write("&nbsp;&nbsp;")
               End If
               output.Write((fieldName + ": "))
               output.RenderEndTag() 'End </B>
               output.RenderEndTag() 'End </TD>
               output.RenderBeginTag(HtmlTextWriterTag.Td)
               _fontAttributeTextBox(index).RenderControl(output) ' Render the text box.
              output.RenderEndTag() 'End </TD>
               output.RenderEndTag() 'End </TR>
            Next index
            output.RenderEndTag() 'End <Table>
            ' Render buttons.
            _parametersReadyButton.RenderControl(output)
            _noParametersInButton.RenderControl(output)
            
            ' Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Render connected Web Part title.
            output.Write((_connectedWebPartLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_connectedWebPartTitle)
            output.RenderEndTag()
            
            ' Required footnote.
            output.Write(("<br><font color=red>" + _requiredInputNotice + "</font>"))
         
         Else
            ' The Web Part isn't connected.
            output.Write(_notConnectedMsg)
         End If
      End Sub 'RenderWebPart
       
      
      ' Create Web Part user interface controls.
      Protected Overrides Sub CreateChildControls()
         ' Create the ParametersInReady button.
         _parametersReadyButton = New Button()
         _parametersReadyButton.ID = "ParametersInReadyButton"
         _parametersReadyButton.Text = "Fire ParametersInReady"
         Controls.Add(_parametersReadyButton)
         
         ' Create the NoParametersIn button.
         _noParametersInButton = New Button()
         _noParametersInButton.ID = "NoParametersInButton"
         _noParametersInButton.Text = "Fire NoParametersIn"
         Controls.Add(_noParametersInButton)
         
         ' Hook up button clicks.
         _parametersReadyButtonClicked = False ' Initialize to false -- user hasn't clicked yet
         AddHandler _parametersReadyButton.Click, AddressOf ParametersInReadyButtonClicked ' listen for Button's click event
         _noParametersInButtonClicked = False ' Initialize to false -- user hasn't clicked yet
         AddHandler _noParametersInButton.Click, AddressOf NoParametersInButtonClicked ' listen for Button's click event
         ' Create Input Field text boxes.
         ' The field names provided by the consumer Web Part needed to be stored in a StateBag because 
         ' the page doesn't have the _fieldList in time after the first postback to create the textbox 
         ' controls and restore their viewstate.
         Dim providerFieldList As String = CStr(ViewState(_fieldListKey))
         Dim requiredFieldList As String = CStr(ViewState(_requiredFieldsKey))
         Dim fieldCount As Integer
         If providerFieldList Is Nothing AndAlso Not (_fieldList Is Nothing) Then
            ' First postback of the page.
            ' Generate controls from the field list provided by the consumer Web Part.
            Dim FieldList As String() = _fieldList
            Dim requiredField As Boolean() = _requiredFieldFlag
            fieldCount = FieldList.Length
            
            _fontAttributeTextBox = New TextBox(fieldCount) {}
            
            Dim vIndex As Integer = 0 'Validation control index
            Dim index As Integer
            For index = 0 To fieldCount - 1
               _fontAttributeTextBox(index) = New TextBox()
               _fontAttributeTextBox(index).ID = FieldList(index)
               Controls.Add(_fontAttributeTextBox(index))               
                      
               ' Populate ViewState providerFieldList item to keep track of field names.
               If index < fieldCount - 1 Then
                  ViewState(_fieldListKey) += FieldList(index).ToString() + ";"
                  ViewState(_requiredFieldsKey) += requiredField(index).ToString() + ";"
               Else
                  ViewState(_fieldListKey) += FieldList(index).ToString()
                  ViewState(_requiredFieldsKey) += requiredField(index).ToString()
               End If
            Next index
         ElseIf Not (providerFieldList Is Nothing) Then
            ' On subsequent postback of page, retrieve field names from StateBag providerFieldList.
            ' Need to parse the providerFieldList information to get the individual fields.
            Dim FieldList As String() = providerFieldList.Split(New [Char]() {";"c})
            Dim requiredField As String() = requiredFieldList.Split(New [Char]() {";"c})
            fieldCount = FieldList.Length
            
            _fontAttributeTextBox = New TextBox(fieldCount) {}
            
            Dim vIndex As Integer = 0
            Dim index As Integer
            For index = 0 To fieldCount - 1
               _fontAttributeTextBox(index) = New TextBox()
               _fontAttributeTextBox(index).ID = FieldList(index)
               Controls.Add(_fontAttributeTextBox(index))
           
            Next index
         End If
      End Sub 'CreateChildControls
      
      
      ' The ParametersInReadyButton OnClick event handler.
      ' <param name="sender">The Button object</param>
      ' <param name="e">The Event Arguments</param>
      Private Sub ParametersInReadyButtonClicked(sender As Object, e As EventArgs)
         _parametersReadyButtonClicked = True 'user clicked button, set to true
      End Sub 'ParametersInReadyButtonClicked
      
      
      ' The NoParametersInButton OnClick event handler.
      ' <param name="sender">The Button object</param>
      ' <param name="e">The Event Arguments</param>
      Private Sub NoParametersInButtonClicked(sender As Object, e As EventArgs)
           _noParametersInButtonClicked = True 'user clicked button, set to true
      End Sub 'NoParametersInButtonClicked
   End Class 'ServerSideParametersInProvider
End Namespace 'ConnectionCodeSamples
// Common .NET required namespaces
using System;
using System.ComponentModel;
using System.Web.UI;

// WebPart required namespaces
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

// Namespace required for ArrayLists
using System.Collections;

// Code Access Security namespaces
using System.Security;
using Microsoft.SharePoint.Utilities;

// Step #1: Reference the Communication namespace.
using Microsoft.SharePoint.WebPartPages.Communication;


namespace ConnectionCodeSamples
{
    // Step #2: Inherit from the WebPart base class and implement the 
    // IParametersInProvider interface.
    public class ServerSideParametersInProvider : WebPart, IParametersInProvider
    {    
        // Step #3: Declare the IParametersInProvider Events
        // Because this class implements the IParametersInProvider 
        // interface, it must 
        // declare the interface members ParametersInReady and 
        // NoParametersIn.  
 
        public event ParametersInReadyEventHandler ParametersInReady;
        public event NoParametersInEventHandler NoParametersIn;    

        // Declare variable for keeping track of the connection state.
        private bool _connected = false;
        private string _connectedWebPartTitle = string.Empty;
        private string _registrationErrorMsg = "An error has occurred trying to register your connection interfaces.";
        private bool _registrationErrorOccurred = false;
        private string _notConnectedMsg = "NOT CONNECTED. To use this Web Part connect it to a ParametersIn Consumer Web Part.";

        // Declare variables for Web Part user interface.
        private string _connectedWebPartLabel = "Connected to Web Part";    
        private Button _parametersReadyButton;
        private bool _parametersReadyButtonClicked = false;
        private Button _noParametersInButton;
        private bool _noParametersInButtonClicked = false;
        private TextBox[] _fontAttributeTextBox;
        private string _fieldListKey = "ProviderFieldList"; //Key for ViewState StateBag
        private string _requiredFieldsKey = "RequiredFields";  //Key for ViewState StateBag
        private string _requiredFieldText = "Required Field";
        private string _requiredInputNotice = "*Required input";

        // Declare variables for Text Box information.
        private string[] _fieldList;
        private string[] _fieldDisplayList;
        private bool[] _requiredFieldFlag;

        // Step #4: Override the EnsureInterfaces method and call 
        // RegisterInterface method.
        // The EnsureInterfaces method is called by the Web Part 
        // infrastructure during the ASP.NET PreRender event 
        // and allows the part to register all of its connection 
        // interfaces.

        public override void EnsureInterfaces()
        {
            // If your Web Part is installed in the bin directory and 
            // the Code Access Security (CAS) setting doesn't 
            // allow Web Part Connections, an exception will be thrown. 
            // To allow your Web Part to behave 
            // well and continue working, a try/catch block should be 
            // used when attempting to register interfaces.
            // Web Part Connections will only work if the level 
            // attribute of the <trust> tag in the 
            // web.config file is set to WSS_Minimal, WSS_Medium, or 
            // Full. By default a new SharePoint site
            // is installed with the trust level set to WSS_Minimal.  
            try
            {
                // Register the IParametersInProvider interface.
                // <param name="interfaceName">Friendly name of the 
                // interface that is being implemented.</param>
                // <param name="interfaceType">Specifies which 
                // interface is being implemented.</param>
                // <param name="maxConnections">Defines how many times 
                // this interface can be connected.</param>
                // <param name="runAtOptions">Determines where the 
                // interface can run.</param>
                // <param name="interfaceObject">Reference to the 
                // object that is implementing this interface.</param>
                // <param name="interfaceClientReference">Name used to 
                // reference the interface on the client.  
                // This is a server side example so the value is set to 
                // empty string.</param>
                // <param name="menuLabel">Label for the interface 
                // which appears in the UI</param>
                // <param name="description">Description of the 
                // interface which appears in the UI</param>
                // <param name="allowCrossPageConnection">Specifies if 
                // the interface can connect to a Web Part
                // on a different page.  This is an optional parameter 
                // with a default of false. Note that only some 
                // server side interfaces are allowed to go cross page 
                // by the Web Part Infrastructure. 
                // The IParametersInProvider interface is allowed to go 
                // cross page.</param>
                RegisterInterface("MyParametersInProviderInterface",        //InterfaceName    
                    InterfaceTypes.IParametersInProvider,                   //InterfaceType
                    WebPart.LimitOneConnection,                             //MaxConnections
                    ConnectionRunAt.Server,                                 //RunAtOptions
                    this,                                                   //InterfaceObject
                    "",                                                     //InterfaceClientReference
                    "Provide Parameters To",                                //MenuLabel
                    "Provides a font parameters to a consumer Web Part.",   //Description
                    true);                                                  //allowCrossPageConnection
            }
            catch(SecurityException se)
            {
                _registrationErrorOccurred = true;
            }
        }


        // Step #5: Override the CanRunAt method.
        // The CanRunAt method is called by the Web Part infrastructure
        // during the ASP.NET PreRender event
        // to determine where the Web Part can run based on its current 
        // configuration.

        public override ConnectionRunAt CanRunAt()
        {
            //This Web Part can run on the server
            return ConnectionRunAt.Server;
        }

        // Step #6: Override the PartCommunicationConnect method.
        // The PartCommunicationConnect method is called by the Web 
        // Part infrastructure to notify the Web Part that it
        // is connected during the ASP.NET PreRender event. Relevant 
        // information is passed to the part such as 
        // the interface it is connected over, the Web Part it is being 
        // connected to, and where the part will be running, 
        // either client or server side. 
        // <param name="interfaceName">Friendly name of the interface 
        // that is being connected</param>
        // <param name="connectedPart">Reference to the other Web Part 
        // that is being connected to</param>
        // <param name="connectedInterfaceName">Friendly name of the 
        // interface on the other Web Part</param>
        // <param name="runAt">Where the interface should 
        // execute</param>

        public override void PartCommunicationConnect(
            string interfaceName,
            WebPart connectedPart,
            string connectedInterfaceName,
            ConnectionRunAt runAt)
        {
            //Keep track of whether connected or not
            if (interfaceName == "MyParametersInProviderInterface")
            {
                //Keep track of the Connection
                _connected = true;
                _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title);
            }
        }
        // Step #7: Implement the PartCommunicationMain() method.
        // The PartCommunicationMain method is called by the Web Part 
        // infrastructure on the client during the ASP.NET PreRender
        // event to allow the part to pass its primary data to the 
        // other connected parts.
        // It is important to always fire either the ParametersInReady 
        // or the NoParametersIn event. Some parts
        // may not behave properly if they are left waiting for this 
        // information.
        // ParametersInReady should be fired to send the parameters.
        // NoParametersIn should be fired to indicate that there is no 
        // change in the parameters.
        public override void PartCommunicationMain()
        {
            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            //Check if connected
            if(_connected)
            {
                // If there is a listener, fire the ParametersInReady 
                // event.
                if(ParametersInReady != null)
                {
                    // Create the ParametersInReadyEventArgs object for 
                    // the ParametersInReady event.
                    ParametersInReadyEventArgs parametersInReadyEventArgs = new ParametersInReadyEventArgs();

                    if(_parametersReadyButtonClicked) //ParametersInReady Button was clicked
                    {
                        // If there is a listener, fire the ParametersInReady event.
                        if(ParametersInReady != null)
                        {
                            // Set the parameter values to the text
                            // box values.
                            if (_fieldList != null)
                            {
                                parametersInReadyEventArgs.ParameterValues = new string[_fieldList.Length];

                                for (int index = 0; index < _fieldList.Length; index++)
                                {
                                    parametersInReadyEventArgs.ParameterValues[index] = _fontAttributeTextBox[index].Text;
                                }

                                // Fire the ParametersInReady event.
                                ParametersInReady(this, parametersInReadyEventArgs);
                            }
                            else //_fieldList is null
                            {
                                // If there is a listener, fire the NoParametersIn event.
                                if(NoParametersIn != null)
                                {
                                    // Fire the event.
                                    NoParametersIn(this, new EventArgs());
                                }
                            }
                            _parametersReadyButtonClicked = false;
                        }
                    }
                    else if(_noParametersInButtonClicked) //NoParametersIn Button was clicked
                    {
                        // If there is a listener, fire the NoParametersIn event.
                        if(NoParametersIn != null)
                        {
                            // Fire the NoParametersIn event.
                            NoParametersIn(this, new EventArgs());

                            _noParametersInButtonClicked = false;
                        }
                    }
                }
            }
        }

        // Step #8: Implement the ParametersInConsumerInit event 
        // handler.
        // The connected consumer part will call this method during its 
        // PartCommunicationInit phase
        // to pass initialization information to the provider Web Part. 
        // The parameters names from the
        // consumer Web Part are passed in. In this example, these 
        // values are used to dynamically 
        // generate the input text boxes in the provider Web Part.
        // <param name="sender">Consumer Web Part</param>
        // <param name="parametersInConsumerInitEventArgs">The args passed by the Consumer</param>

        public void ParametersInConsumerInit(object sender, ParametersInConsumerInitEventArgs parametersInConsumerInitEventArgs)
        {
            // Initialize field lists.
            ParameterInProperty[] paramProps = parametersInConsumerInitEventArgs.ParameterInProperties;

            if (paramProps != null)
            {
                _fieldList = new string[paramProps.Length];
                _fieldDisplayList = new string[paramProps.Length];
                _requiredFieldFlag = new bool[paramProps.Length];

                // Populate field lists.
                for (int index = 0; index < paramProps.Length; index++)
                {
                    _fieldList[index] = paramProps[index].ParameterName;
                    _fieldDisplayList[index] = paramProps[index].ParameterDisplayName;
                    _requiredFieldFlag[index] = paramProps[index].Required;
                }
            }
        }
        
        protected override void RenderWebPart(HtmlTextWriter output)
        {
            // Check for connection interface registration error.
            if (_registrationErrorOccurred)
            {
                output.Write(_registrationErrorMsg);
                return;
            }

            // Check if connected.
            if(_connected)
            {
                // Line break.
                output.RenderBeginTag(HtmlTextWriterTag.Br);
                output.RenderEndTag();

                // Generate input text boxes.
                string fieldName;
                output.RenderBeginTag(HtmlTextWriterTag.Table);
                int vIndex = 0;    //Validation control index
                for (int index = 0; index < _fieldDisplayList.Length; index++)
                {
                    fieldName = _fieldDisplayList[index];
                    
                    output.RenderBeginTag(HtmlTextWriterTag.Tr);
                    output.RenderBeginTag(HtmlTextWriterTag.Td);
                    output.RenderBeginTag(HtmlTextWriterTag.B);

                    // Insert asterisk for required fields.
                    if (_requiredFieldFlag[index])
                        output.Write("<font color=red>*</font>");
                    else
                        output.Write("&nbsp;&nbsp;");
                        output.Write(fieldName + ": ");
                        output.RenderEndTag(); //End </B>
                        output.RenderEndTag(); //End </TD>

                        output.RenderBeginTag(HtmlTextWriterTag.Td);
                        _fontAttributeTextBox[index].RenderControl(output); // Render the text box.

                    output.RenderEndTag(); //End </TD>
                    output.RenderEndTag(); //End </TR>
                }
                output.RenderEndTag(); //End <Table>
                
                // Render buttons.
                _parametersReadyButton.RenderControl(output);
                _noParametersInButton.RenderControl(output);

                // Line break.
                output.RenderBeginTag(HtmlTextWriterTag.Br);
                output.RenderEndTag();

                // Render connected Web Part title.
                output.Write(_connectedWebPartLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_connectedWebPartTitle);
                output.RenderEndTag();

                // Required footnote.
                output.Write("<br><font color=red>" + _requiredInputNotice + "</font>");

            }
            else
            {
                // The Web Part isn't connected.
                output.Write(_notConnectedMsg);
            }

        }

        // Create Web Part user interface controls.
        protected override void CreateChildControls()
        {
            // Create the ParametersInReady button.
            _parametersReadyButton = new Button();
            _parametersReadyButton.ID = "ParametersInReadyButton";
            _parametersReadyButton.Text = "Fire ParametersInReady";
            Controls.Add(_parametersReadyButton);

            // Create the NoParametersIn button.
            _noParametersInButton = new Button();
            _noParametersInButton.ID = "NoParametersInButton";
            _noParametersInButton.Text = "Fire NoParametersIn";
            Controls.Add(_noParametersInButton);

            // Hook up button clicks.
            _parametersReadyButtonClicked = false; // Initialize to false -- user hasn't clicked yet
            _parametersReadyButton.Click += new EventHandler(ParametersInReadyButtonClicked); // listen for Button's click event

            _noParametersInButtonClicked = false; // Initialize to false -- user hasn't clicked yet
            _noParametersInButton.Click += new EventHandler(NoParametersInButtonClicked); // listen for Button's click event

            // Create Input Field text boxes.
            // The field names provided by the consumer Web Part needed to be stored in a StateBag because 
            // the page doesn't have the _fieldList in time after the 
            // first postback to create the text box 
            // controls and restore their viewstate.
            string providerFieldList = (string)ViewState[_fieldListKey];
            string requiredFieldList = (string)ViewState[_requiredFieldsKey];
            int fieldCount;
            if (providerFieldList == null && _fieldList != null)
            {
                // First postback of the page.
                // Generate controls from the field list provided by 
                // the consumer Web Part.
                string[] FieldList = _fieldList;
                bool[] requiredField = _requiredFieldFlag;
                fieldCount = FieldList.Length;
            
                _fontAttributeTextBox = new TextBox[fieldCount];
                int vIndex = 0;  //Validation control index
                for (int index = 0; index < fieldCount; index++)
                {
                    _fontAttributeTextBox[index] = new TextBox();
                    _fontAttributeTextBox[index].ID = FieldList[index];
                    Controls.Add(_fontAttributeTextBox[index]);
                                   
                    // Populate ViewState providerFieldList item to 
                    // keep track of field names.
                    if (index < fieldCount - 1)
                    {
                        ViewState[_fieldListKey] += FieldList[index].ToString() + ";";
                        ViewState[_requiredFieldsKey] += requiredField[index].ToString() + ";";
                    }
                    else
                    {
                        ViewState[_fieldListKey] += FieldList[index].ToString();
                        ViewState[_requiredFieldsKey] += requiredField[index].ToString();
                    }
                }
            }
            else if (providerFieldList != null)
            {
                // On subsequent postback of page, retrieve field names 
                // from StateBag providerFieldList.
                // Need to parse the providerFieldList information to 
                // get the individual fields.
                string[] FieldList = providerFieldList.Split(new Char[] {';'});
                string[] requiredField = requiredFieldList.Split(new Char[] {';'});
                fieldCount = FieldList.Length;

                _fontAttributeTextBox = new TextBox[fieldCount];
                int vIndex = 0;
                for (int index = 0; index < fieldCount; index++)
                {
                    _fontAttributeTextBox[index] = new TextBox();
                    _fontAttributeTextBox[index].ID = FieldList[index];
                    Controls.Add(_fontAttributeTextBox[index]);

                 }
            }
        }

        // The ParametersInReadyButton OnClick event handler.
        // <param name="sender">The Button object</param>
        // <param name="e">The Event Arguments</param>
        private void ParametersInReadyButtonClicked(object sender, EventArgs e)
        {
            _parametersReadyButtonClicked = true; //user clicked button, set to true
        }

        // The NoParametersInButton OnClick event handler.
        // <param name="sender">The Button object</param>
        // <param name="e">The Event Arguments</param>
        private void NoParametersInButtonClicked(object sender, EventArgs e)
        {
           _noParametersInButtonClicked = true; //user clicked button, set to true
        }
    }
}

另请参阅

引用

IParametersInProvider 成员

Microsoft.SharePoint.WebPartPages.Communication 命名空间