Element. Set Binding(DependencyProperty, BindingBase) Method
void SetBinding(DependencyProperty const & dp, BindingBase const & binding);
public void SetBinding(DependencyProperty dp, BindingBase binding);
Public Sub SetBinding (dp As DependencyProperty, binding As BindingBase)
The dependency property identifier of the property that is data bound.
The binding to use for the property.
This example establishes a binding to a dependency property on an object by calling SetBinding.
// 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. TextBlock MyText = new TextBlock(); MyText.SetBinding(TextBlock.TextProperty, b);
'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 Dim MyText As New TextBlock() MyText.SetBinding(TextBlock.TextProperty, b)
This method is a convenience method that calls BindingOperations.SetBinding, passing the current instance as the target parameter.
You can bind to custom dependency properties or custom attached properties, the identifier you pass as the dp parameter doesn't have to be a Windows Runtime defined property.
Whether a binding created from code will be able to use an acting data context depends on object lifetime considerations. For example, a DataContext value that is set from XAML won't be available until the XAML is parsed. In that case you may want to use a Loaded handler to add bindings from code.
Calling the SetBinding method and passing in a new Binding object won't necessarily remove an existing binding. Instead, you should first call the DependencyObject.ClearValue method, then call SetBinding.
Binding to attached properties
You can put data bindings on any attached properties that a target object supports. Technically an DependencyObject supports all the possible attached properties, but you'd usually only set a binding on an attached property that's relevant to that object or your scenario. For example you would set a binding on Grid.Row only if you anticipate that the target element has a Grid parent that will use that info. Specify the dp parameter as the dependency property identifier that exists on the attached property's owner class (for the Grid.Row example, that identifier is Grid.RowProperty ). You won't find that identifier on the target because it's an attached property. For more info on attached properties, see Attached properties overview.