我的Xamarin.Forms应用程序中有一个GridLayout,我想在这里显示网格中的每个元素:
是这样的事实:
通过从数组中获取值并将该值放入单元格来设置每个元素(品牌,图片,价格,卖家等)。
例如,如果我现在只使用品牌和图片(以字符串的形式),我刚刚以两个列表的形式从我的SQL数据库中检索数据: (伪代码)
brand = ["supreme","louisvuitton","addidas","addidas","bape"]
picture = ["hoodie","tshirt","tracksuit","trainers","jacket"]
如何创建一个类/内容页面,该页面将从每个列表中获取下一个字符串,并将一个项目添加到网格中,并在其上添加这些字符串。到目前为止,我尝试创建一个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作为页面上的网格btw。任何帮助将不胜感激:)
答案 0 :(得分:4)
You can create a custom grid view item using a ContentView
.
Doing the UI with the XAML previewer can be a little messy as you will see the view in the context of the phone screen (not as nice as using xib's in iOS for instance).
Start by creating a new XAML file with codebehind.
public partial class MyCustomGridCell : ContentView
{
}
You will need to change the XAML to also be a 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>
Now you have a custom class that you can add to your grid view. In the view that you want this custom object you can import it in the following ways:
XAML:
xmlns:custom="clr-namespace:YOUR_CUSTOM_VIEW_NAMESPACE_HERE"
CS:
using YOUR_CUSTOM_VIEW_NAMESPACE_HERE;
Now you can access your custom view in your ContentPage
. You can add it to your view by the following:
XAML:
<custom: MyCustomGridCell VerticalOptions="FillAndExpand" BackgroundColor="Gray" Padding="2,0,2,2"/>
CS:
//Dont forget to add this to your view (Foo.Children.Add(customView);
MyCustomGridCell customView = new MyCustomGridCell();
If you want to add properties to your custom view, thats not an issue.
If you are using XAML for the UI (which I recommend) you should add the x:name
property to your control:
<Image x:Name="MainImageView"/>
Now add a new public property to your class, and add a setter:
public ImageSource MainImage
{
set
{
MainImageView.Source = value;
}
}
Now when creating your custom view you can call MyCustomGridCell.MainImage = Foo;
By doing your UI this way you make everything super maintainable, you can reuse this view anywhere in your app and only have to make changes to this file once.
I am currently working on an app where I have built my own date picker control (soon to be open sourced). I used this exact approach (I have written this answer from my code) to reuse a view many times (in a loop). Here is a little preview of what I was able to achieve with this method: