Jump to content

For viewers that wanted a more gentle introduction to data binding in XAML, I made a real simple ...


G+_Joe Maruschek
 Share

Recommended Posts

For viewers that wanted a more gentle introduction to data binding in XAML, I made a real simple example.

It wasn't really brought out in the show, but WPF-style data binding allows you to make a simple declaration in XAML that will automatically move data from properties on one object to another. 

 

My example ties the value of a Slider control to the text of a TextBox.  Programmers used to have to write code in event handlers to read the data from one object and set the appropriate property on another.  With WPF-style data binding, you don't need to write that code.  You just "declare" the binding and it is taken care of for you.

 

For this example, create a new WPF project.  Drop a Slider control onto the window and resize it and give it the name "slider".  Also put a TextBox on your window.  Look in the XAML that was created for you and find the Text="TextBox" property.  Replace it with this:  Text="{Binding ElementName=slider, Path=Value}".  The stuff in the curly braces is the data binding statement.  You are telling the system that you want to get data from the element named "slider", and the property you want to get is "Value".  That's it!  Hit F5 and run it.

 

You should see that the TextBox gets automatically updated as you move the slider.  Another neat thing in this case is that the binding is two-way!  If you type in a number from 0 to 10 in the TextBox, and then hit the Tab key, you'll see that the slider moves to the new value you typed in.

 

It easy enough to create this example yourself, but if you don't want to type, you can download my copy below.  I hope you can start to see what a nice tool this declarative-style data binding is.  This is only a small part of what it can do. In another post, I hope to show how you can bind to your own custom object.

http://www.joemaruschek.com/test/SimpleDataBinding.zip

Link to comment
Share on other sites

 Share

×
×
  • Create New...