xamlxamarinmaui

FontImageSource - Color greyed out if ToolBarItem disabled


is possible to grey-out a FontImageSource - Icon if the parent ToolbarItem is disabled?

<ContentPage.ToolbarItems>
    <ToolbarItem
        Command="{Binding StartContainerCommand}"
        CommandParameter="{Binding Container}"
        IsEnabled="{Binding Container.State, Converter={StaticResource IsEqualConverter}, ConverterParameter=exited}"
        Text="Start">
        <ToolbarItem.IconImageSource>
            <FontImageSource FontFamily="faLight"
                    Glyph="&#xf04b;"/>
        </ToolbarItem.IconImageSource>
    </ToolbarItem>
</ContentPage.ToolbarItems>

In the case above the Text of the ToolBarItem is grey but the Icon stays black or white. If possible I would like to do it with styles so I can the same behaviour for all my ToolBarItems.


Solution

  • I ended up using the following solution:

    I created a converter that translates a boolean value to a colour:

    public class EnabledColorConverter : IValueConverter
        {
            public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
            {
                if (value is bool isEnabled && Application.Current?.Resources != null)
                {
                    if (isEnabled)
                    {
                        return Application.Current.RequestedTheme == AppTheme.Dark
                            ? Application.Current.Resources["TextDark"]
                            : Application.Current.Resources["TextLight"];
                    }
                    else
                    {
                        return Application.Current.RequestedTheme == AppTheme.Dark
                            ? Application.Current.Resources["TextDisabledDark"]
                            : Application.Current.Resources["TextDisabledLight"];
                    }
                }
    
                return Colors.Gray; // Fallback color
            }
    
            public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    And used it like that in Xaml:

    <ToolbarItem
        Command="{Binding StartContainerCommand}"
        CommandParameter="{Binding Container}"
        IsEnabled="{Binding Container.State, Converter={StaticResource IsEqualConverter}, ConverterParameter=exited}"
        Text="Start">
        <ToolbarItem.IconImageSource>
            <FontImageSource FontFamily="faLight"
                             Color="{Binding Path=IsEnabled, Source={RelativeSource AncestorType={x:Type ToolbarItem}}, Converter={StaticResource EnabledColorConverter}}"
                             Glyph="&#xf04b;"/>
        </ToolbarItem.IconImageSource>
    </ToolbarItem>