0

It happens that I define a ResourceDictionary for the app colors to use it in XAML files, and have a static class for these colors to use in the cs code: for example:

<ResourceDictionary 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MyApp.Themes.AppTheme">
    <Color x:Key="BrandColor">#ffd92e</Color>
    <Color x:Key="BgColor">#343433</Color>
</ResourceDictionary>

And the opposite class:

public static class AppColors
{
    public static readonly Color BrandColor = (Color)Application.Current.Resources["BrandColor"];
    public static readonly Color BGColor = (Color)Application.Current.Resources["BgColor"];
}

Another scenario,I use icons font in both xaml and cs, in XAML it looks like &#xe8d5;, and in cs it's: \ue8d5 . I want to save them in a file where I can reference them by a meaningful names in XAML and cs like: IconBell = \ue8d5

Is it possible to define resources like those in one place and use them in both XAML and code?

mshwf
  • 7,009
  • 12
  • 59
  • 133
  • Yeah ,it is possible. However be sure that static class `AppColors` can invoke the wanted `Resources[...]` . **Xaml** directly using `{StaticResource TabColor}`,**.CS** using `Resources ["searchBarStyle"]` or your defined static class(Label.TextColor = AppColors.BrandColor ).If need to convert value,you can use `IValueConverter` to do that. – Junior Jiang Mar 14 '19 at 08:12

1 Answers1

0

About the colors issue, it's very easy to solve it. You basically have to create a class containing your colors, and reference it in your XAML, with the x:Static extension.

You can do the same for solving your icons issue, but you'll probably need to create a converter for using it in XAML. For example, the important part of your icon value is the "e8d5" part, but in C# you use the "\u" and in the XAML you use the "&#x". You'll have to create a class with the icons, reference it in the XAML using the x:Static extension and use a converter to convert from C# to XAML, for example:

public class IconConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            string icon = System.Convert.ToString(value);
            return icon.Replace("\u", "&#x");
        }
        catch (Exception)
        {
            throw new InvalidCastException("The value is not a valid string.");
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

With this, you can unify your styles in a unique C# class, and just reference it in your XAML.

Daniel Cunha
  • 616
  • 4
  • 15