共用方式為


FrameworkElement.SetBinding Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Attaches a binding to a FrameworkElement, using the provided binding object, and returns a BindingExpressionBase for possible later use.

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
Public Function SetBinding ( _
    dp As DependencyProperty, _
    binding As Binding _
) As BindingExpressionBase
public BindingExpressionBase SetBinding(
    DependencyProperty dp,
    Binding binding
)

Parameters

Return Value

Type: System.Windows.Data.BindingExpressionBase
A BindingExpressionBase object. See Remarks.

Exceptions

Exception Condition
ArgumentException

binding is specified as TwoWay, but has an empty Path.

-or-

dp or binding parameters are nulla null reference (Nothing in Visual Basic).

Remarks

The returned binding expression is not necessary for many of the common binding scenarios, but is potentially useful for scenarios such as updating the source manually, or getting references to the parent Binding after the expression is created. The BindingExpressionBase class is a base class. In most cases you should attempt to cast the return value to BindingExpression, which is the class that implements the relevant API for the mentioned update or Binding parent scenarios.

For target bindings on dependency properties that are not a property of a FrameworkElement and therefore do not support SetBinding, you can use methods of BindingOperations instead.

NoteNote:

Calling this method and passing in a new Binding object will not necessarily remove an existing binding. Instead, you should use the DependencyObject.ClearValue method.

Examples

The following example establishes a binding to a dependency property on an object by calling SetBinding.

'Create the source string 
Dim s As String = "Hello"

'Create the binding description 
Dim b As New Binding("")
b.Mode = BindingMode.OneTime
b.Source = s

'Attach the binding to the target 
MyText.SetBinding(TextBlock.TextProperty, b)
//Create the source string
string s = "Hello";

//Create the binding description
Binding b = new Binding("");
b.Mode = BindingMode.OneTime;
b.Source = s;

//Attach the binding to the target
MyText.SetBinding(TextBlock.TextProperty, b);

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.