Create a custom Grid Item in Xamarin

柔情痞子 提交于 2019-12-06 00:03:11

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!