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"/>

 

 

其最终效果如下:

 

posted @ 2022-12-20 17:58  盛沧海  阅读(91)  评论(0编辑  收藏  举报