C# WPF Create a Simple Binding Object in Code Behind


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="displayText"/>
        <TextBox Name="sourceInfo"/>
    </StackPanel>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BindingObjectinCodeBehind
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Binding myBinding = new Binding(); // Create the Binding
            myBinding.Source = sourceInfo; // Set the Source (Name of the text box)
            myBinding.Path = new PropertyPath("Text"); // Set the Path
            // Connect the Source and the Target.
            displayText.SetBinding(Label.ContentProperty, myBinding);
            // displayText is the Name of the target control (it is a label)
        }
    }
}

BindingCodeProcess

Leave a comment

Your email address will not be published. Required fields are marked *