Xamarin XAML語言教程ContentView視圖作為自定義視圖的父類

Xamarin XAML語言教程ContentView視圖作為自定義視圖的父類

自定義視圖的父類:ContentView視圖可以作為自定義視圖的父類。

【示例14-2】以下將自定義一個顏色視圖。具體的操作步驟如下:

(1)創建一個Forms Xaml View文件,命名為ColorView。

(2)打開ColorView.xaml文件,編寫代碼,構建自定義顏色視圖。代碼如下:


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文件,編寫代碼,實現一些與顏色視圖相關的屬性。代碼如下:

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文件,編寫代碼,通過顏色視圖實現對內容頁面的布局。代碼如下:


xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:local="clr-namespace:ContentViewCustomControls"

x:Class="ContentViewCustomControls.MainPage">

iOS="0, 20, 0, 0" />

此時運行程序,會看到如圖14.10~14.11所示的效果。


(5)構建更復雜的布局模式:在ContentView中可以包含視圖,還可以包括布局,從而構建更為復雜的布局模式。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容