While working on an application targeted towards WP7 I wanted to have the application change style resource which was attached to a border element based on a value (aka a status) in my view model. After searching around for a bit I was not able to come up w/ a complete end to end solution, only bits and pieces. In order to help the next poor newbie I thought I would post my solution (btw, there may be a MUCH better solution than this out there).
In this sample I simply created a test application based off of the Item List Template which comes out of the box with a few minor changes.
Setting up the XAML
The important item to pay attention to above is the highlighted line. This is the line which will change the border brush via the converter based on the value in the ‘Color’ property in my view model.
Changes to the View model
The code above is the property I added which will allow us to trigger the border brush to determine what style to use
Creating the Converter
The above is a pretty standard converter which uses the IValueConverter interface. The Part in here it pay attention to is how I am grabbing the brush resources out of the App.xaml file (there may be a better way to do this, but i could not find this). What this code does is basically determines which loaded resource to return based on the value passed into the converter
Registering the Converter
Once you create your converter class (see above) you do need to register it in your app.xaml class. Do do this simply follow the logic above.
Creating the Brush Resources
The code above will create the various resources needed to allow us to change the color of our item in XAML
Populating the ‘live data’
The default template for the Item List project has all the data hard wired in the MainViewModel class. I simply added the above logic to populate the color properties.
After you put all the above together you get….
Notice how the little colors next to each item change, this is our doing :) Now of course this is a simple example, but it does go to prove how you can accomplish this.
Till next time,
Posted
07-24-2010 1:51 PM
by
Derik Whittaker