Files
docs-desktop/dotnet-desktop-guide/framework/wpf/data/how-to-create-a-binding-in-code.md
T
Andy De George da363692ff Initial WPF content migrated (#17)
* Reset branch for WPF changes

* Convert BMP to PNG; fix link-out-of-scope err

* Add snippets for WPF... 6794 files!!!!

* Add missing snippets

* update file updated between migration

* Fix paths to include

* update breadcrumb and toc

* fix index links

* fix index links

* fix index links

* fix markdown
2020-09-04 09:46:28 -07:00

2.8 KiB

title, description, ms.date, dev_langs, helpviewer_keywords, ms.assetid
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
csharp
vb
binding data [WPF], creating
data binding [WPF], creating
1a606db9-cf5f-42ed-a1c5-9e4722ec77a0

How to: Create a Binding in Code

This example shows how to create and set a xref:System.Windows.Data.Binding in code.

Example

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]

See also