xamarin 绑定到列表的列表内的对象

wfauudbj  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(113)

我有一个包含字符串的对象A的列表和一个包含字符串的对象B的列表

public  class ObjectA
{
    public string string1 { get; set; }
    public string string2 { get; set; }
    public ObjectB[] objB { get; set; }
}

public class ObjectB
{
    public string string3 { get; set; }
    public string string4 { get; set; }
}

如何在视图中绑定string 3和/或string 4?
在实现我的服务的依赖注入之前,我曾经做过这样的事情:

<CollectionView ItemsSource="{Binding ObjectA}">
  <label Text = "{Binding objB[0].string3}" />
...

现在它在我的XAML文件中给了我一个空引用错误:
对象引用未设置为对象的示例。
在一个列表的列表中绑定一个对象的最佳方法是什么?

gupuwyp2

gupuwyp21#

CollectionView的itemsSource应该绑定到IEnumerable的类型,指定要显示的项目集合。我用下面的代码做了一个演示。
对于xaml,我将ItemsSource绑定到ItemCollection,其中包含ObjectA的集合。

<CollectionView x:Name="mycoll" ItemsSource="{Binding ItemCollection}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Label Text="{Binding objB[0].string3}"/>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

在.cs文件中,设置绑定上下文:

public MainPage()
{
    InitializeComponent();
    this.BindingContext = new MainPageViewModel();
}

在viewModel中,我只添加了一些测试代码:

public class MainPageViewModel
{
    public ObservableCollection<ObjectA> ItemCollection { get; set; } = new ObservableCollection<ObjectA>();

    public MainPageViewModel()
    {
        // add some test code
        ItemCollection.Add(new ObjectA
        {
            string1 = "string1",
            string2 = "string2",
            objB = new ObjectB[]
            {
                new ObjectB
                {
                    string3 = "string31",
                    string4 = "string41"
                },
                new ObjectB
                {
                    string3 = "string32",
                    string4 = "string42"
                }
            }
        });
        ItemCollection.Add(new ObjectA
        {
            string1 = "string1",
            string2 = "string2",
            objB = new ObjectB[]
            {
                new ObjectB
                {
                    string3 = "string31",
                    string4 = "string41"
                },
                new ObjectB
                {
                    string3 = "string32",
                    string4 = "string42"
                }
            }
        });
    }
}

有关更多信息,请参阅Populate a CollectionView with data
希望能成功。

相关问题