xamarin.forms 自定义控件(view)

xamarin.forms中将平时在winform中的控件统一为了view,什么button、label、entry……都直接继承或间接继承于view,故此处所说的自定义控件,及自定义view。

本文主要介绍利用ContentView制作自定义的view。

添加conten view,测试时将其命名为了TopLabel 

添加TopLabel的Xml代码

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
			 xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Name="this"
             x:Class="XamarinAsset.Controls.TopLabel" >
	<Frame Padding="0" CornerRadius="5">
		<Grid  RowDefinitions="20,20" x:Name="Grid"  BackgroundColor="Aqua" Padding="0">
			<Grid.GestureRecognizers>
				<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"  />
			</Grid.GestureRecognizers>
			<Label x:Name="Label1" Grid.Row="0" FontSize="10"  HorizontalOptions="Center" />
			<Label x:Name="Label2" Grid.Row="1" FontSize="10"  HorizontalOptions="Center" />
		</Grid>
	</Frame>
</ContentView>

上述GestureRecoginzers中为这个Grid添加了一个Tapped事件;另在这个TopLabel中添加了两个label,并分别命名。

其code behind代码如下(注意其为命名空间包含):

[DesignTimeVisible(true)]
	public partial class TopLabel : ContentView
	{
		private string title;
		public string Title
		{
			get { return title; }
			set
			{
				if (!string.IsNullOrEmpty(value))
				{
					title = value;
					Label1.Text = value;
				}
			}
		}

		private string text;
		public string Text
		{
			get { return text; }
			set
			{
				if (value != null && !string.IsNullOrEmpty(value))
				{
					text = value;
					Label2.Text = value;
				}
			}
		}


		public event EventHandler<EventArgs> Clicked;
		public TopLabel()
		{
			InitializeComponent();
		}

		private   void TapGestureRecognizer_Tapped(object sender, EventArgs e)
		{
			Clicked?.Invoke(sender, e);
		}

	}

label1主要是为了在顶部显示title,label2是为了显示需要显示的text。

在ContentPage中使用时如下:

1.引入name space如下

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
			 xmlns:control="clr-namespace:XamarinAsset.Controls"
             x:Class="XamarinAsset.Views.AssetScanPage">

2.使用自定义的view

<control:TopLabel x:Name="TlSum" Title="总量" Text="" Grid.Column="1"  Grid.Row="2"  Clicked="TlSum_Clicked"/>

其最终效果如下: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值