Simple Binding in WPF with XAML

For the absolute beginners that don’t know what binding is we will create a little application that takes only 1 minute of your time. We will use a Slider and a TextBlock and place them inside a StackPanel.
Very basic things, no rocket science.

Our goal is to increase or decrease the font size from the TextBlock by moving our Slider left and right.

Here we go:

Open Visual Studio 2008 or Visual Studio 2010 and create a new WPF Application called ‘SimpleBinding‘.

Your Windows1.xaml will look like the code below. We will not use our codebehind (Window1.xaml.cs) file.

<Window x:Class="SimpleBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>

    </Grid>
</Window>

In our next step we replace the Grid with a StackPanel and add 2 StackPanel childs: TextBlock and Slider.

 <Window x:Class="SimpleBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <Slider />
        <TextBlock />
    </StackPanel>
 </Window>
 

Our final step is to bind the TextBlock to the Slider. Therefore we will use a MarkupExtension, you can recognize it by the braces { and }.

<Window x:Class="SimpleBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="Window1" Height="300" Width="300">
     <StackPanel>
        <Slider x:Name="mySlider"
                Minimum="10"
                Maximum="72" />
        <TextBlock Text="This is simple binding!"
                   HorizontalAlignment="Center"
                   FontSize="{Binding ElementName=mySlider, Path=Value}" />
    </StackPanel>
</Window>

Press F5 and test your little WPF application now and see how it works.

We have given our Slider a name ‘mySlider‘ with x:Name=”” attribute so that we can use in our TextBlock.
The Binding itself is very easy. The word Binding tells us that ‘We are going to bind something’, ElementName is used to say ‘What control do we want to bind?’ and the Path tells us ‘What will we use from our ElementName?‘ .

So that’s it, a very simple but powerful binding using only XAML and no C# code in our codebehind file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s