How to: Create a Binding
Microsoft Silverlight will reach end of support after October 2021. Learn more.
A binding is a relationship between a UI property and a CLR object. There are several ways to create a binding object that defines a specific instance of a binding.
To create a binding in XAML
Define the source object.
Public Class Dog Private _DogName As String Public Property DogName() As String Get Return _DogName End Get Set(ByVal value As String) _DogName = value End Set End Property End Classpublic class Dog { public string DogName { get; set; } }Create a reference to the namespace of the source object in XAML.
<UserControl x:Class="BindingXAML.Page" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:BindingXAML">Create an instance of the source object in the Resources section.
<Grid.Resources> <my:Dog x:Key="MyDog" DogName="Spot"/> </Grid.Resources>Bind to the source object by setting either the Source property or the DataContext property. The DataContext is inherited by all the element's children.
<TextBlock Text="{Binding DogName, Source={StaticResource MyDog}, Mode=OneTime}"/>-or-
<TextBlock Text="{Binding DogName, Mode=OneTime}" DataContext="{StaticResource MyDog}"/>
To create a binding by using code
Add the System.Windows.Data namespace
Imports System.Windows.Datausing System.Windows.Data;Define the source object.
Public Class Dog Private _DogName As String Public Property DogName() As String Get Return _DogName End Get Set(ByVal value As String) _DogName = value End Set End Property End Classpublic class Dog { public string DogName { get; set; } }Create the FrameworkElement you want to bind to.
<Grid x:Name="LayoutRoot" Background="White"> <TextBlock x:Name="MyTextBlock" Text="Test"/> </Grid>Create an instance of the source object
Dim MyDog As New Dog() MyDog.DogName = "Spot"Dog MyDog = new Dog(); MyDog.DogName = "Spot";Create a binding object.
Dim MyBinding As New Binding()Binding MyBinding = new Binding();Set the binding properties on the binding object.
MyBinding.Path = New PropertyPath("DogName") MyBinding.Mode = BindingMode.OneTimeMyBinding.Path = new PropertyPath("DogName"); MyBinding.Mode = BindingMode.OneTime;Set the source of the binding by setting either the Source property or the DataContext property. The DataContext is inherited by all the element's children.
MyBinding.Source = MyDogMyBinding.Source = MyDog;-or-
MyTextBlock.DataContext = MyDogMyTextBlock.DataContext = MyDog;Attach the binding to the property of the FrameworkElement.
MyTextBlock.SetBinding(TextBlock.TextProperty, MyBinding)MyTextBlock.SetBinding(TextBlock.TextProperty, MyBinding);