This next blog covers a very trivial but important problem. Important because i think almost everyone would want to override this default behavior of WPF and trivial because the solution is actually pretty simple.Atleast its simple now that i know it. It wasn’t so simple for me earlier though;-)
For this blog i feel pictorial rep is going to be the easiest to follow .OK so the problem is this.
I have a List View with ListView Items and everytime i select an item it turns Blue with a white foreground. Customer says i want Gray background and Blue font (weird choice i know..but then Customer is the King!). So how do we do this??
We basically need to tweak the control template of a ListViewItem. Yeah..ListViewItem.. believe me the ListView is not at fault so changing the background, foreground , selection colour etc of the ListView doesn’t help (you can try it if you have the time :-)).
I think Expression Blend is the easiest way to tweak the control template and though as a developer i swear by VS but Blend does get an extra brownie point for this one.. so the following steps help us here. Open Expression Blend, create a new WPF application and put a ListView control on it. Then go on to add a few ListViewItems as follows.
Do this 2-3 times to add 2-3 List view Items.
Next get the control template of the ListViewItem.
This will create a new style for the ListViewItem. It will ask you where you want to create the style. Since this really isn’t your project the hierarchy doesn’t matter, so keep it in the Window itself
OK. Now Open the Window.xaml. You will find a new style under the Resources section.
The Lines i have highlighted are our culprit. You can see a trigger defined for Selection which sets the background and foreground based on dynamic resources picked up depending on the theme of the OS the app is running on.
So change the trigger values to what YOU want
But this is not enough. You have created a style and given it a key. Which means that this style is applicable only to those ListViewItems to specifically subscribe to it saying Style={StaticResource ListViewItemStyle1}. This is not what we want. We want all the Items to follow this style. So remove the “x:key= ListViewItemStyle1” from the style definition.
This will make the style applicable to all the UI elements of Target Type= “ListViewItem”(lower in the heirarchy ofcourse)
Now run the app (f5) and select any ListView Item
Now pick up this style definition and paste it in your app.xaml/ window.xaml depending on the heirarchy you want!
This works for ListView/ TreeView … hope it helps you somehow!
Till next time!
Cennest