TOC

This article is currently in the process of being translated into Dutch (~34% done).

Data binding:

Hello, bound world!

Zoals we deze tutorial gestart zijn met het klassieke "Hello, world!" voorbeeld, zo zullen we je nu laten zien, hoe gemakkelijk het is om data binding in WPF te gebruiken met een "Hello, bound world!"- voorbeeld. Laten we er meteen induiken en het daarna uitleggen:

<Window x:Class="WpfTutorialSamples.DataBinding.HelloBoundWorldSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="HelloBoundWorldSample" Height="110" Width="280">
    <StackPanel Margin="10">
		<TextBox Name="txtValue" />
		<WrapPanel Margin="0,10">
			<TextBlock Text="Value: " FontWeight="Bold" />
			<TextBlock Text="{Binding Path=Text, ElementName=txtValue}" />
		</WrapPanel>
	</StackPanel>
</Window>

Dit eenvoudige voorbeeld laat zien hoe we de waarde van het TextBlock binden aan de Text property van de TextBox. Zoals je kunt zien in het screenshot, wordt het TextBlock automatisch bijgewerkt als je tekst invult in de TextBox. In een "non-bound" (niet verbonden) wereld, zouden we moeten luisteren naar een event op de TextBox. Het TextBlock iedere keer moeten worden geüpdatet moeten, als de tekst wijzigt. Met data binding kan deze verbinding gemaakt worden in de markup.

The syntax of a Binding

All the magic happens between the curly braces, which in XAML encapsulates a Markup Extension. For data binding, we use the Binding extension, which allows us to describe the binding relationship for the Text property. In its most simple form, a binding can look like this:

{Binding}

This simply returns the current data context (more about that later). This can definitely be useful, but in the most common situations, you would want to bind a property to another property on the data context. A binding like that would look like this:

{Binding Path=NameOfProperty}

The Path notes the property that you want to bind to, however, since Path is the default property of a binding, you may leave it out if you want to, like this:

{Binding NameOfProperty}

You will see many different examples, some of them where Path is explicitly defined and some where it's left out. In the end it's really up to you though.

A binding has many other properties though, one of them being the ElementName which we use in our example. This allows us to connect directly to another UI element as the source. Each property that we set in the binding is separated by a comma:

{Binding Path=Text, ElementName=txtValue}

Summary

This was just a glimpse of all the binding possibilities of WPF. In the next chapters, we'll discover more of them, to show you just how powerful data binding is.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!