Dynamically change style for SelectedItem of ComboBox

In this case, I wanted to set a DataTrigger to change the style of the selectedItem of combo box when the binding return a particular value. Sounds very simple, right? Well, it didn’t turn not as such. This is because the selectedItem style is kind of locked and also redraws only on SelectedItemChanged event.

What it means is if you are dynamically adding combobox in a list control like treeview, then after adding it with a particular style, if you want to change the style of selectedItem(or for that matter all items) in combo box when a certain value changes(or even on certain eventtrigger), that style gets applied but not displayed for selectedItem. You have to select another item from combo box to see the applied style. In other words, if i have all items as blue and when data changes for a property from true to false, I want all items to become red. Then they all will go read except that the selectedItem will stay blue. If you dropdown the list, then you can see that the selectedItem in the dropdown has also gone red but not in the “selected” state, it still blue as currently selected. If you select any other item, then the new item is red and you can then go back to the initial selectedItem, then it will also come red but without doing this exercise, the selectedItem will automatically not turn red.

I spent almost an hour trying to sort this out and finally found a way out. Instead of changing the entire datatemplate, we ended up defining a textbox in datatemplate for combobox and inside that datatemplate, we attached a converter to the texbblock to change the property data to a property value i.e. red color in this case. But i wasn’t so straighforward, we had to set the binding on the Foreground property of textblock(you can chose any other property here), then Set the path as DataContext.IsTrue (IsTrue) is the public property on each item object bound to each item of combo i.e. not on the parent viewmodel that has collection bound to the combo’s itemsource property. Then set the relative source to the AncesterType={x:Type ComboBox} and Mode=FindAncestor, this mapped back to the parent combo box i.e. one level up from the each item of combobox and then attach the convertor as well. The converter will then check the value, do the necessary custom work i.e. return a foreground colour red in this case which will be finally applied to the Foreground color where all this super complex properties are set to.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s