WPF Data Binding in Code Behind


This entry is part 4 of 7 in the series WPF Data Binding

As we saw in the previous post, defining a binding by using XAML is easy. You can do it from the code-behind instead. This is pretty easy as well and offers the exact same possibilities as when you’re using XAML.

In the code-behind, we create a Binding instance. We specify the Path we want directly in the constructor, in this case “Text”, since we want to bind to the Text property. We then specify a Source, which for this example should be the TextBox control. Now WPF knows that it should use the TextBox as the source control, and that we’re specifically looking for the value contained in its Text property.

In the last line, we use the SetBinding method to combine our newly created Binding object with the destination/target control, in this case the TextBlock (lblValue). The SetBinding() method takes two parameters, one that tells which dependency property that we want to bind to, and one that holds the binding object that we wish to use.

Below is the XAML code.

<Window x:Class="BindingCodeBehind.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:BindingCodeBehind"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="BindingCodeBehind" Height="250" Width="400">
    <StackPanel Margin="10">
        <TextBox Name="txtValue" Background="LightGreen" />
        <WrapPanel Margin="0,10">
            <TextBlock Text="Value: " FontWeight="Bold" />
            <TextBlock Name="lblValue" />
        </WrapPanel>
    </StackPanel>
</Window>

Below is the C# code.

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

namespace BindingCodeBehind
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SetupBinding();
        }
        public void SetupBinding()
        {
            Binding binding = new Binding("Text");
            binding.Source = txtValue;
            lblValue.SetBinding(TextBlock.TextProperty, binding);
        }
    }
}
Series Navigation<< WPF DataContext Targeting the Main WindowWPF the UpdateSourceTrigger Property >>