Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 在Xamarin中创建自定义网格项_Class_Xamarin_Xamarin.forms_Grid - Fatal编程技术网

Class 在Xamarin中创建自定义网格项

Class 在Xamarin中创建自定义网格项,class,xamarin,xamarin.forms,grid,Class,Xamarin,Xamarin.forms,Grid,我在Xamarin.Forms应用程序中有一个GridLayout,我希望网格中的每个元素都显示在这里: 例如: 每个元素(品牌、图片、价格、卖家等)都是通过从数组中获取一个值并将该值放入单元格来设置的 例如,如果我现在只使用品牌和图片(以字符串的形式),并且我刚刚从SQL数据库中以两个列表的形式检索了数据: (伪代码) 我如何创建一个类/内容页,从每个列表中获取下一个字符串,并向网格中添加一个包含这些字符串的项。到目前为止,我已经尝试创建一个c#类,如下所示: class Item {

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

例如:

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

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

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

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
    };

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

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

使用XAML预览器进行UI可能会有点混乱,因为您将在手机屏幕的上下文中看到视图(例如,不如在iOS中使用xib)

首先使用codebehind创建一个新的XAML文件

public partial class MyCustomGridCell : ContentView
{
}
您还需要将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>
政务司司长:

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

XAML:

如果要将属性添加到自定义视图,这不是问题

如果您对UI使用XAML(我建议这样做),则应将
x:name
属性添加到控件:

<Image x:Name="MainImageView"/>
现在,在创建自定义视图时,可以调用
MyCustomGridCell.MainImage=Foo

通过这样做你的UI,你可以让一切都超级可维护,你可以在你的应用程序中的任何地方重用这个视图,并且只需要对这个文件做一次更改

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

xmlns:custom="clr-namespace:YOUR_CUSTOM_VIEW_NAMESPACE_HERE"
using YOUR_CUSTOM_VIEW_NAMESPACE_HERE;
<custom: MyCustomGridCell VerticalOptions="FillAndExpand" BackgroundColor="Gray" Padding="2,0,2,2"/>
//Dont forget to add this to your view (Foo.Children.Add(customView);
MyCustomGridCell customView = new MyCustomGridCell(); 
<Image x:Name="MainImageView"/>
public ImageSource MainImage
{
    set
    {
        MainImageView.Source = value;
    }
}