Apply static resource style to UIElement created in converter
-
27-10-2019 - |
Question
I am binding the ItemsSource
of an ItemsControl
to a Textbox
and then using a converter to create UIElement
objects based on the Text
property of the Textbox
. I also have a static resource style that I want to apply to the elements I create.
The problem I'm having is how to set the style of the items created in the converter to the static resource since I don't have access to the static resources in my converter class.
Solution
To use StaticResource
in the Converter
you could send the Style
as ConverterParameter
.
If you're already using the ConverterParameter
you could make the Converter
derive from DependencyObject
, add a Dependency Property and set it to the Style
on the creation of the Converter
.
But the easiest solution is probably to use DynamicResource
instead if you know the key of the resource.
The following Xaml
<UIElement Style="{DynamicResource styleKey}" />
is equivalent to the following C# code
myUIElement.SetResourceReference(StyleProperty, "styleKey");
OTHER TIPS
Mission impossible! :) you can use ConverterParameter as your static resource, I think. and all will be ok!