Export (0) Print
Expand All

How to: Create a Binding

Silverlight

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

  1. Define the source object.

    
        public class Dog
        {
            public string DogName { get; set; }
        }
    
    
    
    
  2. Create a reference to the namespace of the source object in XAML.

    
    <UserControl x:Class="BindingXAML.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:my="clr-namespace:BindingXAML">
    
    
    
  3. Create an instance of the source object in the Resources section.

    
    <Grid.Resources>
        <my:Dog x:Key="MyDog" DogName="Spot"/>
    </Grid.Resources>
    
    
    
  4. 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

  1. Add the System.Windows.Data namespace

    
    using System.Windows.Data;
    
    
    
  2. Define the source object.

    
    public class Dog
    {
        public string DogName { get; set; }
    }
    
    
    
  3. Create the FrameworkElement you want to bind to.

    
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="MyTextBlock" Text="Test"/>
    </Grid>
    
    
    
  4. Create an instance of the source object

    
    Dog MyDog = new Dog();
    MyDog.DogName = "Spot";
    
    
    
  5. Create a binding object.

    
    Binding MyBinding = new Binding();
    
    
    
  6. Set the binding properties on the binding object.

    
    MyBinding.Path = new PropertyPath("DogName");
    MyBinding.Mode = BindingMode.OneTime;
    
    
    
  7. 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 = MyDog;
    
    
    

    -or-

    
    MyTextBlock.DataContext = MyDog;
    
    
    
  8. Attach the binding to the property of the FrameworkElement.

    
    MyTextBlock.SetBinding(TextBlock.TextProperty, MyBinding);
    
    
    

Reference

Concepts

Community Additions

ADD
Show:
© 2015 Microsoft