How to create a Bindable property with dynamicResource extension?

PedroCondePedroConde PTMember ✭✭
edited December 2016 in Xamarin.Forms

On trying to use Dynamic resouce with this binding property:

public static readonly BindableProperty ColorBindableProperty= BindableProperty.Create("Color", typeof (Color), typeof (CustomView), default(Color));
public Color Color
            get { return (Color)GetValue(ColorBindableProperty); }
            set { SetValue(ColorBindableProperty, value); }

I'm getting this error

{DynamicResource} can only be used with dependency property

The xaml is the following:

       Color="{DynamicResource ColorKey}"
... />

Any ideas?


  • ChaseFlorellChaseFlorell CAInsider, University mod

    Not sure the purpose of DynamicResource

    <ns:CustomView Color="{Binding Color}" />
  • PedroCondePedroConde PTMember ✭✭

    @ChaseFlorell, I want to set the Color property of the CustomView to a dynamic value that is updated on runtime, after a service call

  • ChaseFlorellChaseFlorell CAInsider, University mod

    Right, but isn't it easy enough to query the value from your ViewModel and just set the Color property?

  • PedroCondePedroConde PTMember ✭✭

    CustomView is agnostic of the ViewModel, it doesn't know it. And it should not know it.

    This is working for instance with a Grid's backgroundColor property. I can set it to the '{DynamicResource ColorKey}'.
    But not working on the Bindable property created by me...

    Did I made my point? Can you understand the issue?

  • JerajoJerajo Member ✭✭
    edited June 15

    Hi @PedroConde. I had the same issue but I solved it by using a bindable property of type object.

        public object Color
            get => GetValue(ColorProperty);
            set => SetValue(ColorProperty, value);
        private static readonly BindableProperty ColorProperty =
            BindableProperty.Create(nameof(Color), typeof(object), typeof(CustomView),
            Color.Transparent, BindingMode.OneWay);

    Then I created a method to convert the DynamicResource to type Color.

        private Color GetColor(object value)
            if (value is Color color) return color;
            else if (value is DynamicResource resource) 
                return (Color)App.Current.Resources[resource.Key]; // get the DynamicResource 
            else if (value is string code) return Color.FromHex(code); 
            else  return Color.Transparent;

    Here is how to use it. On any part of your custom control you can call the GetColor method.

    var color = GetColor(this.Color);

    Now you can subscribe to DynamicResources changes and use the color.

           Color="{DynamicResource ColorKey}"
     ... />

    You can do the same with any other type.

Sign In or Register to comment.