I have several hundred brushes defined in Application.xaml. These are shared resources for several user controls in project. They all have patterned keys: ch_YSD, ch_HJU, ch_IYO…
I try to use these brushes in datatemplate. In datatemplate I have access to variable part of brushes keys, that is in data template I can get YSD, HJU, IYO, etc. as string.
How can I bind to particular brush resource from xaml?
Currently I have such solution: in style use data trigger to set required property to specified brush depending on bound string (variable part of keys).
I am not satisfied with this solution because list of brushes in Application.xaml will increase often.
I am not sure if I should go for code behind as I want to use memory saving benefit of shared resources in Application.xaml.
It’s a kind of task that looks simple, but actually has no perfect solution (or I didn’t find it). The first approach is to use value converter. But it doesn’t work! We need to set resource reference which can’t be done correctly by converter. So, I think the right way is attached behavior. But you should know about limitation: there can be only one property to apply resource to. Perhaps you could avoid this limitation depending on your requirements.
Attached behavior allows you to reference resource with a specified named to a specified dependency property:
Behavior can be used in XAML like the following:
The code above is equivalent to: