如何在Xamarin中解决错误'属性为null或不是IEnumerable'

时间:2016-11-23 03:41:54

标签: c# xaml xamarin

我正在尝试制作以下内容

<platform:TablePrac.Columns>
    <platform:TextColumn Caption="it"/>
    <platform:TextColumn Caption="is"/>
</platform:TablePrac.Columns>

但是,当我运行此错误'属性列为空或不是IEnumerable'时。

代码流程如下。

当我写上面的.xaml代码时,名为Columns的属性设置了值。 (列定义如下)

public List<Column> Columns
{
    set
    {
        columns = value;
        SetValue(ColumnsProperty, value);
    }
    get
    {
        return (List<Column>)GetValue(ColumnsProperty);
    }
}

public class Column
{
    public string caption;
    public Type type;
}

public class TextColumn : Column
{
    public TextColumn() : base()
    {
        this.type = typeof(string);
    }

    public TextColumn(string cap) : base()
    {
        this.caption = cap;
        this.type = typeof(string);
    }

    public string Caption
    {
        set { caption = value; }
        get { return caption; }
    }

    public Type Type
    {
        get { return type; }
    }
}

作为非常相似的案例,定义StackLayout并在其中创建新视图

<StackLayout>
    <Label Text="it"/>
    <Label Text="is"/>
</StackLayout>

与.cs代码相同,如下所示

StackLayout stack = new StackLayout
{
    Children =
    {
        new Label { Text = "it"},
        new Label { Text = "is"}
    }
};

所以,我想让属性Columns在.xaml中作为StackLayout工作,但我不知道如何。我花了两天时间来解决它....我需要你的帮助 谢谢。

(另外,StackLayout和Children定义如下

StackLayout

public class StackLayout : Layout<View>

布局

[Xamarin.Forms.ContentProperty("Children")]
public abstract class Layout<T> : Layout, IViewContainer<T>
where T : View
{
    public IList<T> Children { get; }

    ...
}

1 个答案:

答案 0 :(得分:3)

问题不是IEnumerable而是Null值。

在Xamarin.Forms中使用BindableProperty时,可以为Property指定默认值。例如,给出默认值&#39; new List()&#39;解决这个问题。 Follwing是我的代码,如果你有同样的问题,请检查它。

之前:

--deleted

之后:

public static readonly BindableProperty ColumnsProperty = BindableProperty.Create("Columns", typeof(List<Column>), typeof(TablePrac));

public List<Column> Columns
{
    set
    {
        SetValue(ColumnsProperty, value);
    }
    get
    {
        return (List<Column>)GetValue(ColumnsProperty);
    }
}

我将Columns的返回值类型转换为 IList ,因为在#Stack; StackLayout的孩子&#39;的情况下,孩子的类型是 IList 类型。没有其他原因。