C# WPF Create a Simple Binding Object in Code Behind


This entry is part 5 of 18 in the series C# WPF

This example comes from the book Illustrated WPF starting on page 198, which is in chapter 8. Creating a binding with XAML is easy. To see what is going on, this example creates a binding in the code behind. It uses a label and a text box that sit on top of a stack panel. To do this, let’s build the window shown below. It contains a StackPanel with a Label at the top and a TextBox below it. Whatever text you type in the TextBox immediately shows in the Label above it, as well.

BindingCodeBehind

The markup for the window is the following. It’s very simple; it just specifies the creation of the Label and the TextBox and gives them names so they can be referenced from the code-behind.

<Window x:Class="BindingObjectinCodeBehind.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BindingObjectinCodeBehind"
        mc:Ignorable="d"
        Title="Binding" Height="150" Width="225">
    <StackPanel>
        <Label Name="targetLabel"/>
        <TextBox Name="sourceTextBox"/>
    </StackPanel>
</Window>

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace BindingObjectinCodeBehind
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Binding myBinding = new Binding(); // Create the Binding
            myBinding.Source = sourceTextBox; // Set the Source (Name of the text box)
            myBinding.Path = new PropertyPath("Text"); // Set the Path
            // Connect the Source and the Target.
            targetLabel.SetBinding(Label.ContentProperty, myBinding);
        }
    }
}

BindingCodeProcess

  • Create a new binding object
  • Name of the source
  • Property of the Source
  • Attach it to the target (run SetBinding() method on target)
Series Navigation<< C# WPF First Window IntroductionC# WPF Data Binding >>