Xamarin 如何使用自定义数据创建 customCell

Xamarin How to create customCell with custom data

据我了解,我们使用方法"SetBinding"获取数据 但是,如果我对数据使用自定义 class,我就没有那种方法。我该如何扩展我的 class?

var image = new Image();
var nameLabel = new Label();
var typeLabel = new Label();

//set bindings
nameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
typeLabel.SetBinding(Label.TextProperty, new Binding("Type"));
image.SetBinding(Image.SourceProperty, new Binding("Image"));

我的class:

public class TextTable
    {
        public string Name { get; set; }
        public string[] Column { get; set; }
        public DataFormat[] Data { get; set; }
     }

SetBinding 是 UI 对象的方法

首先,你真的应该考虑在 XAML 中做你的 UI,它很好地分离了关注点(UI 和数据等)并使绑定非常容易(与代码相比后面)。

我将 post 一个完整数据绑定场景的示例(使用自定义对象),但是请记住您的问题涉及基本数据绑定原则。您可能应该去查找许多在线资源,我将从 data binding docs for xamarin.

开始

模特:

public class MyObject
{
    public string Title { get; set; }
    public string Description { get; set; }
    //This class can have any property you want
}

我想在列表视图中显示此数据:

<ListView ItemsSource="{Binding TheItemSource}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Title}" Detail="{Binding Description}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我将此 ListView 绑定到 public ObservableCollection<MyObject>,一旦我设置了它,我就可以将我的 UI 绑定到 MyObject 下定义的任何属性。

在您的视图模型中,您需要绑定一个 属性,在这种情况下,我们需要一个 ObservableCollection(我们也可以使用 List)。

private ObservableCollection<MyObject> _theItemSource;
public ObservableCollection<MyObject> TheItemSource
{
    get
    {
        return _theItemSource;
    }
    set
    {
        //Your view model will need to implement INotifyPropertyChanged
        //I use prism for MVVM so I have a different method than normal to notify the view that a property has changed (its normally OnPropertyChanged()).
        SetProperty(ref _theItemSource, value);
    }
}

现在,您应该在 ViewModel 中设置 _theItemSource 的值,当列表视图要求 TheItemSource 的值时将使用该值。

此时您可以用数据填充您的列表,它将显示在我们之前在 XAML 中定义的列表视图中。

我再次强烈建议您在 XAML 中创建您的 UI,这样绑定会容易得多!