Converter to set FontImageSource

Jassim Al Rahma 1,521 Reputation points
2023-03-30T12:54:48.4966667+00:00

Hi,

I have the following Image control:

<Image WidthRequest="25" HeightRequest="25" Margin="10,0,0,0" VerticalOptions="Center">
<Image.Source>
    <FontImageSource FontFamily="FontSolid" Glyph="{StaticResource IconAdd}" Color="Black" />
</Image.Source>
</Image>

I want the Glyph to be set automatically based on a Label, for example, if the Labelnickname.Text = "Add" then the Gylph should be IconAdd otherwise it should be IconEdit

How can I achieve this, please?

Thanks,

Jassim

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,857 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,146 Reputation points Microsoft Vendor
    2023-03-31T06:52:09.4733333+00:00

    Hello,

    Firstly, I'm not sure how you define the StaticResource IconAdd for Glyph. You could refer to the official sample to create a static class:

    static class IconFont
    {
        public const string IconAdd= "\uf641";
        public const string IconEdit = "\uf2b9";
    }
    

    Then, you can try Binding value converters and refer to the following code :

    Converter class

    public class FontImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
           return (string)value == "Add" ? IconFont.IconAdd : IconFont.IconEdit;
        }
       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();// oneway binding, this method will not be called.
        }
    }
    
    

    XMAL

        <ContentPage.Resources>
            <local:FontImageConverter  x:Key="fontImageConverter" />
        </ContentPage.Resources>
    <Image >
                <Image.Source>
                    <FontImageSource FontFamily="XXX" Glyph="{Binding Source={x:Reference LabelNickname},
                                        Path=Text,
                                        Converter={StaticResource fontImageConverter}}" Color="Black" />
    <!-- I change the fontfamily and add black color so that I can see the Glphy lightly-->
    
               </Image.Source>
    </Image>
    
    

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful