Attaches a binding to a FrameworkElement, using the provided binding object.
The dependency property identifier of the property that is data bound.
The binding to use for the property.
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.
Note 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.
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.
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. MyText.SetBinding(TextBlock.TextProperty, b);
Minimum supported client
Minimum supported server
|Windows Server 2012|
Build date: 11/16/2013