BrandonReinhart
Topic Author
Posts: 29
Joined: 10 Jan 2025, 17:02

How do I FindResource in a Converter in Unity?

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.
    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.
 
BrandonReinhart
Topic Author
Posts: 29
Joined: 10 Jan 2025, 17:02

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

13 Mar 2025, 15:22

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.
 
User avatar
sfernandez
Site Admin
Posts: 3363
Joined: 22 Dec 2011, 19:20

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

14 Mar 2025, 19:21

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);

Who is online

Users browsing this forum: No registered users and 7 guests