简体   繁体   中英

While Binding Collection of Colors System.ArgumentException is occuring

I have a custom view in my PCL project in Xamarin.Forms. I am not able bind a collection of colors in Xaml to a bindable object in my CustomView.

I have set the binding as in below in xaml:

<local:CustomView x:Name="customView"  ColorPalette="{Binding Colors}"/>

My CustomView is as below:

public class CustomView : View
{
    public CustomView()
    {

    }

    public static void OnColorsChanged(BindableObject bindable, object oldValue, object newValue)
    {
        // Some Code
    }

    public static readonly BindableProperty ColorsPaletteProperty =
        BindableProperty.Create("ColorPalette", typeof(IEnumerable<Color>), typeof(CustomView), new List<Color>(){ Color.FromRgb(0, 0, 0),
            Color.FromRgb(251, 176, 59)}, BindingMode.Default, null, OnColorsChanged);

    public IEnumerable<Color> ColorPalette
    {
        get { return (IEnumerable<Color>)GetValue(ColorsPaletteProperty); }
        set { SetValue(ColorsPaletteProperty, value); }
    }
}

While performing the binding in Xaml, I get an exception "System.ArgumentException: Object of type 'Xamarin.Forms.Binding' cannot be converted to type 'Xamarin.Forms.Color'".

But when I bind the Colors in using SetBinding in code behind it is working properly.

Code Behind:

 //Binding using SetBinding is working where as {Binding Colors} in xaml is not working

customView.SetBinding<ViewModel>(CustomView.ColorsPaletteProperty, vm => vm.Colors);

Colors is a collection of colors of type IEnumerable / IList / List / ObservableCollection.

Any help is appreciated.

Regards,

Nitish

A custom view embedded in another view will inherit the binding context of the parent view. Are you setting the binding context of the view to a viewmodel that has a Colors property? Some more code samples of where you're setting the binding context and of your viewmodel might be helpful.

Your property name is ColorPalette but your bindable property name has not followed the standards, it should be like "ColorPaletteProperty" not "ColorsPaletteProperty" you have added an "s" to the "Color" which is wrong. So can you remove that and check? it should work, let me know if this helps.

Thanks, Michael

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM