I'm trying to setup static resources for different states in my business entities. The idea being that I can use a value converter to take the business entity and return the corresponding background brush depending on an algorithm. I'd like the resources to be static so I can design them in the designer and switch them over manually to preview what it would look like during development, but be able to use them programatically.
The aim would be to have something along these lines:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var data = value as DummyData;
if (data == null)
return null;
//Find resources
if (data.VarianceAmount >= 0)
return StaticResources.HighBackground;
else
return StaticResources.LowBackground;
}
If the static resources are declared in the page / control / framework element in the hierachy, how do I access it from inside the value converter? I've set my value converter to a DependencyObject, but i'm not sure how to navigate the hierachy from there.
The trick is to pass the desired resource values into the converter when you create it.
For example,
public class CustomColorConverter : IValueConverter
{
public SolidColorBrush HighBackground { get; set; }
public SolidColorBrush LowBackground { get; set; }
// remaining implementation...
}
Then in your Xaml resources section, you'd declare it something like this (using your own resources of course):
<local:CustomColorConverter x:Key="BackgroundConverter"
HighBackground="{StaticResource HighlightBrush}"
LowBackground="{StaticResource NormalBrush}" />
This has the advantage of being reusable. You can create another instance with a new key and define different brushes.
Additionally, this can work for just about anything, not just SolidColorBrushes; you can define complete Styles or Templates as well.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With