- C# WPF Introduction
- C# WPF First Program
- C# WPF without XAML – Window Class
- C# WPF First Window Introduction
- C# WPF Create a Simple Binding Object in Code Behind
- C# WPF Data Binding
- C# WPF Data Binding and Triggers
- C# WPF Data Binding and Binding Direction
- C# WPF Data Binding and Triggers MouseOvers
- C# WPF Value Converters
- C# WPF ComboBox Control
- C# WPF Bindings and ItemsControls
- C# WPF Styles
- C# WPF RGB Colour Viewer
- C# WPF XAML Background Colour
- C# WPF Events
- C# WPF Dynamic Binding to External Objects
- C# WPF Multiple Bindings on an Object
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.
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); } } }
- Create a new binding object
- Name of the source
- Property of the Source
- Attach it to the target (run SetBinding() method on target)