In the previous post on making fancy layouts with Xamarin Forms we saw how you can design a Dashboard style application that stretches to fill any device size. However one of the challenges of the particular design we chose for Falafel 2 Go was the need to support the concept of an Image Button, where both the icon and the text work as a single control to launch an activity.

Xamarin Forms does provide an ImageCell control, which can be used in a TableView to render both text and image as a single control. However, this control is laid out horizontally with the text positioned on the right side of the image as you would expect for a list of items.

While we could likely acheive a more precise layout with a custom renderer, we found a much more elegnat, and more importantly, reusable option by instead creating a User Control.

XAML User Controls

The concept of User Controls is not new, and exists in many different platforms including Silverlight, XAML for Windows and Windows Phone as well as Web Forms. Basically the idea is to create a small container for a collection of controls that will be reused as a single control throughout the application. The User Control exposes properties allowing you to reuse the control while allowing each instance of the control to have different settings, layout, or behavior.

Because User Controls are so useful (and simple to create) on other platforms, we were pleased and relieved to discover that Xamarin Forms supports them as well. While we weren’t able to find any documentation on the matter, with some experimentation we discovered the solution below. If there are official docs for this, please let me know in the comments so I can link to them!

Creating the Xamarin Forms User Control

Begin by adding a regular Xamarin Forms XAML Control to the project. By default this creates a ContentPage. For our layout, we want the image and text to flow vertically, so it makes sense to use a StackLayout, which is why we named the control StackLayoutButton. We can then change the XAML so that the control is also a StackLayout, as shown in the complete example later in the post.

In addition, the code-behind class by default doesn’t inherit from any base class. Usually you would modify this to be a ContentPage to both match the XAML definition as well as expose the properties and methods of the base control. However, because we’re using a StackLayout, we simply needed to update this to inherit from that control. This is also shown later in the full code-behind snippet.

By changing the class of the control we can proceed to add additional XAML controls to the StackLayout to make up the overall User Control. In this case we’re adding both the Image and Label controls as shown in the complete code below, completing the self-contained StackLayoutButton. Notice that we can define the properties for each control so that they are global to all instances of the button, eliminating the need to set them over and over for each one.

But what if we want to vary the properties on a specific control?

Accessing Child Controls and Properties

Because the individual controls are defined inside the StackLayout, we don’t have direct access to them from the User Control when we add them to the main page. However, we can workaround this by adding get and set properties to the StackLayoutButton which expose either the individual properties of a control, or the entire control itself.

If you review the full code of the StackLayoutButton code-behind below, you see that we’ve created two additional public properties. The TextColor sets or returns the value of the Label property so it can be set at the UserControl level. The other Label control returns the actual Label itself, so that we could potentially access and modify any property of that control.

This is demonstrated in the code-behind for the ActivitesPage control, where we access an instance of the StackLayoutButton by name, and can then access theTextControl property to set the BackgroundColor of that control.

Here’s what the final example page looks like. We’ve combined the two options to change both the Font color and the BackgroundColor using the exposed properties for specific buttons.

At last, here are the complete code samples for the controls, starting with the XAML for the StackLayoutButton:

<?xml version=“1.0” encoding=“utf-8” ?>
<StackLayout xmlns=“http://xamarin.com/schemas/2014/forms”
xmlns:common=“clr-namespace:Falafel2GoV2.Common;assembly=Falafel2GoV2”
xmlns:x=“http://schemas.microsoft.com/winfx/2009/xaml”
x:Class=“Falafel2GoV2.Controls.StackLayoutButton“>
<Image x:Name=“Icon” Source=“{Binding Icon}” />
<Label x:Name=“Text” Text=“{Binding Title}” HorizontalOptions=“Center” LineBreakMode=“NoWrap” Font=“Small” TextColor=“{x:Static common:ColorResources.ListTitle}” />
</StackLayout>

The StackLayoutButton code-behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;namespace Falafel2GoV2.Controls
{
public partial class StackLayoutButton : StackLayout
{
public Color TextColor
{
get { return this.Text.TextColor; }
set { this.Text.TextColor = value; }
}public Label TextControl
{
get { return this.Text; }
set { this.Text = value; }
}public StackLayoutButton()
{
InitializeComponent();
}
}
}

The ActivitiesView XAML:

<?xml version=“1.0” encoding=“UTF-8“?>
<ContentPage xmlns=“http://xamarin.com/schemas/2014/forms”
xmlns:x=“http://schemas.microsoft.com/winfx/2009/xaml”
xmlns:common=“clr-namespace:Falafel2GoV2.Common;assembly=Falafel2GoV2”
xmlns:controls=“clr-namespace:Falafel2GoV2.Controls;assembly=Falafel2GoV2”
x:Class=“Falafel2GoV2.Views.ActivitiesPage”
Title=“{Binding ViewName}”
BackgroundImage=“mainBack.png“>
<ContentPage.Content>
<StackLayout Orientation=“Vertical” Padding=“{x:Static common:PaddingResources.MainBody}“>
<Label Text=“{Binding ViewName}” Font=“42” IsVisible=“{Binding IsWindowsPhone}” />
<ActivityIndicator IsRunning=“{Binding IsLoading}” IsVisible=“{Binding IsLoading}” Color=“{x:Static common:ColorResources.ActivityIndicator}” /><Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=“*” />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=“3*” />
<RowDefinition Height=“4*” />
</Grid.RowDefinitions><Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=“*” />
<ColumnDefinition Width=“*” />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=“*” />
</Grid.RowDefinitions><controls:StackLayoutButton BindingContext=“{Binding Blog}” TextColor=“Blue” /><controls:StackLayoutButton x:Name=“RedButton”Grid.Column=“1” BindingContext=“{Binding Training}” TextColor=“Red” />
</Grid><

Grid Grid.Row=“1“>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=“*” />
<ColumnDefinition Width=“*” />
<ColumnDefinition Width=“*” />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height=“*” />
<RowDefinition Height=“*” />
</Grid.RowDefinitions><

controls:StackLayoutButton BindingContext=“{Binding Facebook}” />
<controls:StackLayoutButton Grid.Column=“1” BindingContext=“{Binding Twitter}” />
<controls:StackLayoutButton Grid.Column=“2” BindingContext=“{Binding Google}” /><

controls:StackLayoutButton Grid.Row=“1” BindingContext=“{Binding Eventboard}” />
<controls:StackLayoutButton Grid.Row=“1” Grid.Column=“1” BindingContext=“{Binding Website}” />
<controls:StackLayoutButton Grid.Row=“1” Grid.Column=“2” BindingContext=“{Binding Contact}” />
</Grid>
</Grid>
</StackLayout>
</ContentPage.Content>
</ContentPage>

And finally the ActivitiesView code-behind:

using System;
using System.Collections.Generic;
using Falafel2GoV2;
using Falafel2GoV2.Views;
using Xamarin.Forms;
using Falafel2GoV2.ViewModels;
using Falafel2GoV2.Controls;
using Falafel2GoV2.Models;namespace Falafel2GoV2.Views
{
public partial class ActivitiesPage : ContentPage
{private ActivitiesViewModel vm;public ActivitiesPage()
{
InitializeComponent();
vm = new ActivitiesViewModel();
this.BindingContext = vm;RedButton.TextControl.BackgroundColor =Color.Black;
}}
}

Wrapping Up and Next Steps

By creating a User Control we were able to eliminate the need to define several copies of controls, encapsulating the controls into a single container so it can be defined with a single line a code. In addition, because we added properties to the control, we allow each instance of the control to have its own properties, and even behaviors.

The only thing left is to allow the user to Tap this new custom button to launch the activity. We’ll see how easy this is to do in the next post.

Until then, as always, I hope this was helpful!

from:http://blog.falafel.com/creating-reusable-xaml-user-controls-xamarin-forms/

Creating Reusable XAML User Controls with Xamarin Forms的更多相关文章

  1. Xamarin.Forms移动开发系列4 :XAML基础

    摘要 本文介绍Xamarin.Forms创建用户界面的语言:XAML基础部分. 前言 本文介绍Xamarin.Forms定义用户界面的语言:XAML. 本篇篇幅较长,主要讲述XAML语法,以及对其他基 ...

  2. Xamarin.Forms之XAML

    官网参考 XAML基础知识 XAML(eXtensible Application Markup Language)可扩展应用程序标记语言,允许开发者在Xamarin.Forms应用中采用标记而不是代 ...

  3. Xamarin.Forms 开发资源集合(复制)

    复制:https://www.cnblogs.com/mschen/p/10199997.html 收集整理了下 Xamarin.Forms 的学习参考资料,分享给大家,稍后会不断补充: UI样式 S ...

  4. Xamarin.Forms 开发资源集合

    收集整理了下 Xamarin.Forms 的学习参考资料,分享给大家,稍后会不断补充: UI样式 Snppts: Xamarin Forms UI Snippets. Prebuilt Templat ...

  5. Xamarin.Forms介绍

    On May 28, 2014, Xamarin introduced Xamarin.Forms, which allows you to write user-interface code tha ...

  6. Xamarin.Forms 简介

    An Introduction to Xamarin.Forms 来源:http://developer.xamarin.com/guides/cross-platform/xamarin-forms ...

  7. Add AI feature to Xamarin.Forms app

    Now, AI is one of important technologies.Almost all platforms have API sets of AI. Following list is ...

  8. 在 Xamarin.Forms 实现密码输入EntryCell

    在 Xamarin.Forms 中,我们通常使用 TableView 来构建输入表单.Xamarin 为我们提供了 EntryCell 用于输入文本,但是其并不支持密码输入,即密码掩码.这里要对 En ...

  9. Xamarin.Forms 自定义控件(呈现器和效果)

    Xamarin.Forms 使用目标平台的本机控件呈现用户界面,从而让 Xamarin.Forms 应用程序为每个平台保留了相应的界面外观.凭借效果,无需进行自定义呈现器实现,即可自定义每个平台上的本 ...

随机推荐

  1. web.xml 配置中classpath: 与classpath*:的区别——(十一)

    首先 classpath是指 WEB-INF文件夹下的classes目录 解释classes含义: 1.存放各种资源配置文件 eg.init.properties log4j.properties s ...

  2. python格式化输出【转】

    今天写代码时,需要统一化输出格式进行,一时想不起具体细节,用了最笨的方法,现在讲常见的方法进行一个总结. 一.格式化输出 1.整数的输出 直接使用'%d'代替可输入十进制数字: >>> ...

  3. 什么是Jupyter Notebook?

    Jupyter Notebook, 以前又称为IPython notebook,是一个交互式笔记本, 支持运行40+种编程语言. 可以用来编写漂亮的交互式文档. Linux下, Jupyter Not ...

  4. C# Message类的属性Msg所关联的消息ID

    C# Message类的属性Msg所关联的消息ID   https://msdn.microsoft.com/en-us/library/windows/desktop/ms645606(v=vs.8 ...

  5. js中的事件委托或是事件代理详解(转载)

    起因: 1.这是前端面试的经典题型,要去找工作的小伙伴看看还是有帮助的: 2.其实我一直都没弄明白,写这个一是为了备忘,二是给其他的知其然不知其所以然的小伙伴们以参考: 概述: 那什么叫事件委托呢?它 ...

  6. PHP 5.2、5.3、5.4、5.5、5.6 对比以及功能详解

    php5.2.x php5.3.x php5.4.x php5.5.x php5.6.x 对比详解 截至目前(2014.2), PHP 的最新稳定版本是 PHP5.5, 但有差不多一半的用户仍在使用已 ...

  7. Java编程的逻辑 (3) - 基本运算

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  8. Angular 2.0--1

    Angular 2.0 从0到1 (五) 第一节:Angular 2.0 从0到1 (一)第二节:Angular 2.0 从0到1 (二)第三节:Angular 2.0 从0到1 (三)第四节:Ang ...

  9. Codeforces Round #475 (Div. 2) D. Destruction of a Tree

    题意:给你一棵树, 只能删度数为偶数的点, 问你能不能将整个图删完, 如果能输入删除的顺序. 思路:对于一棵树来说, 如果里面的点的个数是偶数个则肯定不可能, 偶数个点有奇数条边,而你每次删只能删偶数 ...

  10. P1508 Likecloud-吃、吃、吃 DP

    题目背景 问世间,青春期为何物? 答曰:“甲亢,甲亢,再甲亢:挨饿,挨饿,再挨饿!” 题目描述 正处在某一特定时期之中的李大水牛由于消化系统比较发达,最近一直处在饥饿的状态中.某日上课,正当他饿得头昏 ...