当绑定颜色集合系统.参数异常发生时



我在Xamarin.Forms中的PCL项目中有一个自定义视图。我无法将 Xaml 中的颜色集合绑定到自定义视图中的可绑定对象。

我已经在 xaml 中设置了绑定,如下所示:

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

我的自定义视图如下:

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); }
    }
}

在 Xaml 中执行绑定时,我收到异常"System.ArgumentException:类型为'Xamarin.Forms.Binding'的对象无法转换为类型'Xamarin.Forms.Color'"。

但是当我在它后面的代码中使用 SetBinding 绑定颜色时,它工作正常。

代码隐藏:

 //Binding using SetBinding is working where as {Binding Colors} in xaml is not working
customView.SetBinding<ViewModel>(CustomView.ColorsPaletteProperty, vm => vm.Colors);

颜色是 IEnumerable/IList/List/ObservableCollection 类型的颜色集合。

任何帮助,不胜感激。

问候

尼蒂什

嵌入在另一个视图中的自定义视图将继承父视图的绑定上下文。是否将视图的绑定上下文设置为具有 Colors 属性的视图模型?有关设置绑定上下文的位置和视图模型的更多代码示例可能会有所帮助。

您的属性名称是 ColorPalette,但您的可绑定属性名称没有遵循标准,它应该像"ColorPaletteProperty"而不是"ColorsPaletteProperty",您在"颜色"中添加了一个"s",这是错误的。那么您可以将其删除并检查吗?它应该有效,让我知道这是否有帮助。

谢谢迈克尔

最新更新