Xamarin XAML語言教程ContentView視圖作為自定義視圖的父類
自定義視圖的父類:ContentView視圖可以作為自定義視圖的父類埃撵。
【示例14-2】以下將自定義一個顏色視圖赵颅。具體的操作步驟如下:
(1)創(chuàng)建一個Forms Xaml View文件,命名為ColorView暂刘。
(2)打開ColorView.xaml文件饺谬,編寫代碼,構(gòu)建自定義顏色視圖谣拣。代碼如下:
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ContentViewCustomControls.ColorView">
WidthRequest="70"
HeightRequest="70" />
FontSize="Large"
VerticalOptions="CenterAndExpand" />
VerticalOptions="CenterAndExpand" />
(3)打開ColorView.xaml.cs文件募寨,編寫代碼族展,實現(xiàn)一些與顏色視圖相關(guān)的屬性。代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ContentViewCustomControls
{
public partial class ColorView : ContentView
{
string colorName;
ColorTypeConverter colorTypeConv = new ColorTypeConverter();
public ColorView()
{
InitializeComponent();
}
//顏色名稱
public string ColorName
{
set
{
colorName = value;
colorNameLabel.Text = value;
Color color = (Color)colorTypeConv.ConvertFromInvariantString(colorName);
boxView.Color = color;
colorValueLabel.Text = String.Format("{0:X2}-{1:X2}-{2:X2}",
(int)(255 * color.R),
(int)(255 * color.G),
(int)(255 * color.B));
}
get
{
return colorName;
}
}
}
}
(4)打開MainPage.xaml文件拔鹰,編寫代碼仪缸,通過顏色視圖實現(xiàn)對內(nèi)容頁面的布局。代碼如下:
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ContentViewCustomControls"
x:Class="ContentViewCustomControls.MainPage">
iOS="0, 20, 0, 0" />
此時運(yùn)行程序列肢,會看到如圖14.10~14.11所示的效果恰画。
(5)構(gòu)建更復(fù)雜的布局模式:在ContentView中可以包含視圖,還可以包括布局瓷马,從而構(gòu)建更為復(fù)雜的布局模式锣尉。