【问题标题】:Xamarin How to create customCell with custom dataXamarin 如何使用自定义数据创建 customCell
【发布时间】:2018-09-25 19:59:13
【问题描述】:

据我了解,我们使用“SetBinding”方法获取数据 但是,如果我对数据使用自定义类,我就没有那个方法。我该如何扩展我的课程?

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

我的班级:

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

【问题讨论】:

  • "SetBinding(...) 是 Xamarin.Forms.BindableObject 上的扩展方法。Label 和 Image 继承自 BindableObject,因此您可以在它们上调用 SetBinding。在您的类中没有包含的类型一个名为“SetBinding”的方法。

标签: listview xamarin binding custom-cell


【解决方案1】:

SetBinding 是一个 UI 对象的方法

【讨论】:

    【解决方案2】:

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

    Whilst not the same as your question, I posted an answer here which is similar to your question and would be worth reading.

    我将发布一个完整数据绑定方案的示例(使用自定义对象),但请记住,您的问题涉及基本数据绑定原则。有很多在线资源你可能应该去查找,我会从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&lt;MyObject&gt;,一旦我设置了它,我就可以将我的 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,它使绑定变得更加容易!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2017-05-02
      • 2013-08-13
      相关资源
      最近更新 更多