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);//通过此调用申明的Clicked事件 } }
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="总量" Clicked="TlSum_Clicked"/>
其最终效果如下:
*****有道无术,术尚可求;有术无道,止于术。*****
标签:
xamarin.forms
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!