在Xamarin中创建自定义网格项

ker*_*s78 3 grid class xamarin xamarin.forms

我的Xamarin.Forms应用程序中有一个GridLayout,我希望这里显示的网格中的每个元素:

在此处输入图片说明

成为这样的实例:

网格中的每个单元

通过从数组中获取值并将该值放入单元格来设置每个元素(品牌,图片,价格,卖家等)的位置。

例如,如果我现在仅使用品牌和图片(以字符串的形式),而我刚刚从SQL数据库中以两个列表的形式检索了数据:(伪代码)

brand = ["supreme","louisvuitton","addidas","addidas","bape"]
picture = ["hoodie","tshirt","tracksuit","trainers","jacket"]
Run Code Online (Sandbox Code Playgroud)

我如何创建一个类/内容页面,该页面将从每个列表中获取下一个字符串,并将带有这些字符串的项目添加到网格中。到目前为止,我已经尝试过创建ac#类,如下所示:

class Item
{
    public string brand { get; set; }
    public string picture { get; set; }

    Button Background = new Button
    {
        BackgroundColor = Color.FromHex("#EEEEEE"),
    };
    Label label = new Label
    {
        Text = brand
    };
    Label label2 = new Label
    {
        Text = picture
    };
Run Code Online (Sandbox Code Playgroud)

我知道我必须将“按钮”和“标签”添加到某种“布局”中,但我不知道如何首先将我的项目放置到网格中。我正在使用xaml作为带有网格的页面。任何帮助,将不胜感激 :)

Axe*_*sta 5

您可以使用创建自定义网格视图项目ContentView

使用XAML预览器进行UI可能会有些混乱,因为您会在电话屏幕的上下文中看到视图(例如,不如在iOS中使用xib那样好)。

首先创建一个带有代码隐藏的新XAML文件。

public partial class MyCustomGridCell : ContentView
{
}
Run Code Online (Sandbox Code Playgroud)

您将需要将XAML更改为 ContentView

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="NAMESPACEHERE">
    <ContentView.Content>
        <!-- Your View here, This is done the same as any other UI-->
    </ContentView.Content>
</ContentView>
Run Code Online (Sandbox Code Playgroud)

现在您有了一个自定义类,可以将其添加到网格视图中。在需要该自定义对象的视图中,可以通过以下方式导入它:

XAML:

xmlns:custom="clr-namespace:YOUR_CUSTOM_VIEW_NAMESPACE_HERE"
Run Code Online (Sandbox Code Playgroud)

CS:

using YOUR_CUSTOM_VIEW_NAMESPACE_HERE;
Run Code Online (Sandbox Code Playgroud)

现在,您可以在中访问您的自定义视图ContentPage。您可以通过以下方式将其添加到视图中:

XAML:

<custom: MyCustomGridCell VerticalOptions="FillAndExpand" BackgroundColor="Gray" Padding="2,0,2,2"/>
Run Code Online (Sandbox Code Playgroud)

CS:

//Dont forget to add this to your view (Foo.Children.Add(customView);
MyCustomGridCell customView = new MyCustomGridCell(); 
Run Code Online (Sandbox Code Playgroud)

如果要向自定义视图添加属性,那就不是问题。

如果将XAML用于UI(建议使用),则应将x:name属性添加到控件中:

<Image x:Name="MainImageView"/>
Run Code Online (Sandbox Code Playgroud)

现在,向您的班级添加一个新的公共属性,并添加一个setter:

public ImageSource MainImage
{
    set
    {
        MainImageView.Source = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在创建自定义视图时,您可以调用 MyCustomGridCell.MainImage = Foo;

通过以这种方式执行UI,您可以使所有内容都具有超级可维护性,您可以在应用程序中的任何位置重复使用此视图,而只需对该文件进行一次更改。

我目前正在开发一个自己的日期选择器控件(即将开源)的应用程序。我使用了这种精确的方法(我已经从代码中写出了这个答案)来多次(循环)重用视图。这是我使用此方法可以实现的功能的一些预览:

使用可重复使用的内容视图的自定义日期选择器控件