How do I FindResource in a Converter in Unity?
Posted: 13 Mar 2025, 15:11
I want to implement a converter from an enum to a style. It seems like I should be able to do something like Application.Current... but this doesn't work in Unity? I could also pass in a framework element, but don't see how.
x:Reference isn't supported.
Code: Select all
public class CheckResultToDiceTextStyle : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var resourceKey = "DiceGreen";
var result = (AttributeCheckResult) value;
switch (result)
{
case AttributeCheckResult.Success:
resourceKey = "DiceGreen";
break;
case AttributeCheckResult.Failure:
resourceKey = "DiceRed";
break;
}
if (parameter is FrameworkElement frameworkElement)
{
return frameworkElement.FindResource(resourceKey);
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}Code: Select all
<TextBlock x:Name="DiceResult" Text="{Binding Roll}" Margin="0,6,0,0"
Style="{Binding Roll,
Converter={StaticResource CheckResultToDiceTextStyle},
ConverterParameter={x:Reference RootGrid}}"
Width="40" TextAlignment="Center" Opacity="0">