Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to point one Color resource to another Color resource in Xamarin.Forms?

I am building a Xamarin Forms Application and I am currently drawing up my application Resources, mainly my colours.

For example I have the following:

  <Color x:Key="Slate">#404040</Color>
  <Color x:Key="Blue">#458623</Color>

  <Color x:Key="SelectedItemColour">#458623</Color>

As you can see my SelectedItemColour is the same as the Blue.

I have tried the following but it didn't work:

  <Color x:Key="Slate">#404040</Color>
  <Color x:Key="Blue">#458623</Color>

  <Color x:Key="SelectedItemColour" Color="{StaticResource Blue}"/>

I know if WPF you can do the answer stated here

Is it possible to point a Colour Resource to another Colour Resource in Xamarin.Forms?

like image 649
User1 Avatar asked Jan 27 '16 15:01

User1


1 Answers

This may be an old question, but I was trying to accomplish this same thing for a project today and wanted a more elegant solution than the one proposed here. There doesn't seem to be a way to accomplish it purely with XAML, but this is the solution I ended up using.

First, I defined a utility class named ColorReference:

public class ColorReference : INotifyPropertyChanged
{
    private Color color = Color.Black;

    public Color Color
    {
        get => this.color;
        set
        {
            this.color = value;
            this.OnPropertyChanged();
        }
    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    [ NotifyPropertyChangedInvocator ]
    protected virtual void OnPropertyChanged([ CallerMemberName ] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion

    public static implicit operator Color(ColorReference colorReference) => colorReference.Color;
}

I'm not 100% positive that the INotifyPropertyChanged implementation is necessary but I figured it couldn't hurt (potentially allowing changing the color at runtime; I haven't tested this).

To use it, simply use it as a resource in a ResourceDictionary:

<Color x:Key="FirstColor">#51688f</Color>
...
<utility:ColorReference x:Key="SomeOtherColorName" Color="{StaticResource FirstColor}" />

In my use case, I'm using it to style Telerik controls with colors defined in my theme so that if I make a new theme, I don't need to copy the same color value all over the place. The obvious downside is that for any type other than Color, a new class would need to be defined, but I doubt I will need too many types to be aliased like this. Hopefully this helps someone else in the future trying to do the same thing I'm doing.

like image 188
Arcanox Avatar answered Oct 19 '22 12:10

Arcanox