Page 1 of 1

How do I FindResource in a Converter in Unity?

Posted: 13 Mar 2025, 15:11
by BrandonReinhart
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.
    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();
    }
            <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">
x:Reference isn't supported.

Re: How do I FindResource in a Converter in Unity?

Posted: 13 Mar 2025, 15:22
by BrandonReinhart
Ah! Nevermind. Once again overthinking it. I was able to easily find the resource I needed using the main window which I have statically accessible.

Re: How do I FindResource in a Converter in Unity?

Posted: 14 Mar 2025, 19:21
by sfernandez
In Unity you can search for the GameObject that contains the ViewComponent (the MainCamera?), and then do something like this:
...
NoesisView view = mainCamera.GetComponent<NoesisView>();
return view.Content.FindResource(resourceKey);