title | description | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|---|
How to: Create a Binding in Code |
Learn how to create a binding in code in a Windows Presentation Foundation application by calling the SetBinding method directly. |
03/30/2017 |
|
|
1a606db9-cf5f-42ed-a1c5-9e4722ec77a0 |
This example shows how to create and set a xref:System.Windows.Data.Binding in code.
The xref:System.Windows.FrameworkElement class and the xref:System.Windows.FrameworkContentElement class both expose a SetBinding
method. If you are binding an element that inherits either of these classes, you can call the xref:System.Windows.FrameworkElement.SetBinding%2A method directly.
The following example creates a class named, MyData
, which contains a property named MyDataProperty
.
[!code-csharpCodeOnlyBinding#DataObject] [!code-vbCodeOnlyBinding#DataObject]
The following example shows how to create a binding object to set the source of the binding. The example uses xref:System.Windows.FrameworkElement.SetBinding%2A to bind the xref:System.Windows.Controls.TextBlock.Text%2A property of myText
, which is a xref:System.Windows.Controls.TextBlock control, to MyDataProperty
.
[!code-csharpCodeOnlyBinding#1] [!code-vbCodeOnlyBinding#1]
For the complete code sample, see Code-only Binding Sample.
Instead of calling xref:System.Windows.FrameworkElement.SetBinding%2A, you can use the xref:System.Windows.Data.BindingOperations.SetBinding%2A static method of the xref:System.Windows.Data.BindingOperations class. The following example, calls xref:System.Windows.Data.BindingOperations.SetBinding%2A?displayProperty=nameWithType instead of xref:System.Windows.FrameworkElement.SetBinding%2A?displayProperty=nameWithType to bind myText
to myDataProperty
.
[!code-csharpCodeOnlyBinding#BOSetBinding] [!code-vbCodeOnlyBinding#BOSetBinding]