I am currently reading an excellent book by Charles Petzold called "Application = Code + Markup". The current chapter I am reading is called Dependency Objects. I have decided to try and practically implement DependencyObjects as part of the Impilo Health Management System.
One of my projects requirements is an application to be installed in locker rooms of a health club. On the screen it must show all the lockers in the locker room and then mark the lockers that are already occupied. A user must also be able to select a locker and authenticate his identity and then the application must open the selected locker and reserve it for the member. Once the member is finished exercising, he can just authenticate his identity and the locker must open for him to remove his belongings. For the purpose of this blog, I will only explain my experiences trying to implement the Locker class and how I bind it to the graphics representation of the lockers.
I first created a class called Locker with dependency properties for isAvailable, occupiedBy and Description
1) Define the property
public static readonly DependencyProperty isAvailableProperty;
public bool isAvailable
{
set
{
SetValue(isAvailableProperty, value);
}
get
{
return (bool)GetValue(isAvailableProperty);
}
}
2) Register the property in the constructor
isAvailableProperty = DependencyProperty.Register("isAvailable",typeof(bool),typeof(Locker));
For the purpose of this blog, I will only bind a single locker object to a checkbox. This will allow me to click on the checkbox and verify that my locker object is updated.
The following code assumes that a checkbox and a button are already created:
locker = new Locker();
locker.isAvailable = true;
locker.Description = "Locker 1";
Binding bind = new Binding();
bind.Source = locker;
bind.Path = new PropertyPath(Locker.isAvailableProperty);
cbAvailable.SetBinding(CheckBox.IsCheckedProperty, bind);
To verify that the binding works, I added the following event to a button:
if ( locker.isAvailable )
MessageBox.Show("Available");
else
MessageBox.Show("Not Available");
If you run the following application you can toggle the checkbox and verify the state by clicking on the button. DependencyObjects/DependencyProperties are very easy to use and implement. Binding to these properties are natively supported by WPF. Other advantages of using DependencyObject are:
- Default values
- Expressions
- Inheritance
- Styling
- Property Invalidation
If there is a demand, I will try and explain some of these features in more detailed in future blogs...
For more information about Impilo Health Management project visit www.codeplex.com/impilo