Jump to content

Here is another gentle example of data binding in WPF, this time with a custom object For my ex...


G+_Joe Maruschek
 Share

Recommended Posts

Here is another gentle example of data binding in WPF, this time with a custom object.  For my example I made a Task class that has three private fields: name, owner, and dueDate, and three public properties: Name, Owner, and DueDate.  The code for that class is stored in the Task.cs file.  In the code-behind file for my MainWindow, I create a Task object and set its properties.  (I just finished watching Agents of SHIELD, so I figured this would be a task on Coulson's to-do list.) At the same time, I set a property of the MainWindow, DataContext, to point to my task object.  DataContext is a special property used by the data binding system.  You usually set it to an instance of your object you want to bind to.

 

Over in the XAML, I have two TextBoxes and a DatePicker.  I put data binding statements in each of them. In the first TextBox, I say Text="{Binding Path=Name}".  The next TextBox I put Text="{Binding Path=Owner}".  On the DatePicker, I put Text="{Binding Path=DueDate, Mode=TwoWay}".  Note that I didn't say what object to bind to.  That's taken care of by setting the DataContext property.  All I need to do on each element is just put what field I want to bind it to.  And that's it!  Hit F5 to run.

 

You'll see that the text boxes and the date picker are automatically filled in with the data I set on the object.  The text boxes will also automatically change the data in the object.  As you type in new values on the form and tab off of each field, you can click that button at the bottom to view what the current properties of the task object are.

 

By the way, even though these examples are all WPF windows programs, the data binding syntax works in the new Windows Store/Modern/Metro apps too, as well as Windows Phone 8.1 apps.

 

Hopefully I can post another example that shows what happens when you use data binding with a list of objects.

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

Link to comment
Share on other sites

 Share

×
×
  • Create New...