XAMARIN For VS2019之跨平台APP入门基础

本文详细介绍了使用Xamarin.Forms进行跨平台APP开发的基础知识,包括HelloWord、布局(ContentView、Frame、ScrollView、StackLayout、RelativeLayout、AbsoluteLayout、Grid)、页面(ContentPage、NavigationPage、MasterDetailPage、TabbedPage、CarouselPage)和通用界面元素(Image、BoxView、Label、Entry、Editor、Button、Switch、Slider、Stepper、ProgressBar、ActivityIndicator、警告视图、操作表视图)。内容深入浅出,适合初学者学习。
摘要由CSDN通过智能技术生成

第一章:HelloWord
一、基础知识:1、主程序前台文件:App.xaml
2、主程序后台文件:App.xaml.cs
3、主程序入口方法:App()
4、主程序入口主页面:MainPage
主程序前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App4.App">
    <Application.Resources>

    </Application.Resources>
</Application>

主程序后台文件

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App4
{
    public partial class App : Application
    {
        public App()
        {
          InitializeComponent();
          MainPage = new ContentPage
           {
                Content = new Label
               {
                    Text = "您好!",
                   FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                   VerticalOptions = LayoutOptions.CenterAndExpand,
                   HorizontalOptions = LayoutOptions.CenterAndExpand,
                },
           };
    }
}

第二章:布局
一、内容视图:ContentView,只能放一个控件

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App4.MainPage">
    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="*">


            </RowDefinition>


        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>


            <ColumnDefinition Width="*">

            </ColumnDefinition>
        </Grid.ColumnDefinitions>
        <BoxView Color="Red" Grid.Row="0" Grid.Column="0"></BoxView>
        <BoxView Color="Blue" Grid.Row="0" Grid.Column="1"></BoxView>
        <BoxView Color="Yellow" Grid.Row="1" Grid.Column="0"></BoxView>
        <BoxView Color="Green" Grid.Row="1" Grid.Column="1"></BoxView>
    </Grid>

</ContentPage>

二、框架:Frame
Frame被称为框架,是最简单的一种布局方式,它被定制为屏幕上的一个空白备用区域,之后开发者可以在其中填充一个单一元素,属性Padding默认为20,四个角带弧度。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App4.MainPage">
   <Frame>
      <Image x:Name="Myimage">
      </Image>
   </Frame>
</ContentPage>

三、滚动视图:ScrollView
ScrollView滚动视图,用于显示多于一个屏幕的内容,超出屏幕范围的内容可以通过滚动查看。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App4.MainPage">
   <ScrollView>
      <Label>
        世界你好
      </Label>
   </ScrollView>
</ContentPage>

四、堆栈布局:StackLayout
StackLayout堆栈布局,非常常用的布局方式,可以极大的简化跨平台用户界面的搭建,堆栈布局的子元素按照添加到界面中的顺序一个接一个的摆放,XF中堆栈布局分为两种:垂直布局和水平布局。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App4.MainPage">
   <StackLayout VericalOptions="Center" Orientation="Horizontal">
      <Label TextColor="Red">第一个标签</Label>
      <Label TextColor="Black">第二个标签</Label>
      <Label TextColor="Yellow">第三个标签</Label>
   </StackLayout>
</ContentPage>

五、相对布局:RelativeLayout
RelativeLayout相对布局,可以将其理解成以某一个元素为参照物来定位的布局方式,根据参照物不同,相对布局可以分为两种:一种是相对于父元素的布局,一种是控件之间的相对布局。

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App4
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            //相对于父控件的布局
            RelativeLayout rl = new RelativeLayout();
            rl.Children.Add(new BoxView { Color = Color.Accent, WidthRequest = 150, HeightRequest = 150, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }, Constraint.Constant(0), Constraint.Constant(0));
            rl.Children.Add(new BoxView { Color = Color.Red, WidthRequest = 150, HeightRequest = 150, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }, Constraint.RelativeToParent(Parent => { return Parent.Width - 150; }), Constraint.Constant(0));
            rl.Children.Add(new BoxView { Color = Color.Blue, WidthRequest = 150, HeightRequest = 150, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }, Constraint.Constant(0),Constraint.RelativeToParent(Parent => { return Parent.Height - 150; }));
            rl.Children.Add(new BoxView { Color = Color.Yellow, WidthRequest = 150, HeightRequest = 150, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }, Constraint.RelativeToParent(Parent => { return Parent.Width - 150; }), Constraint.RelativeToParent(Parent => { return Parent.Height - 150; }));
            //相对于父窗口控件的布局
            RelativeLayout rl = new RelativeLayout();
            rl.Children.Add(new BoxView { Color = Color.Accent, WidthRequest = 150, HeightRequest = 150, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }, Constraint.RelativeToParent(Parent=> { return Parent.Width / 2-75; }), Constraint.RelativeToParent(Parent => { return Parent.Height / 2-75; }));
            //相对于控件的布局
            Label lb = new Label { Text = "这是一个方块", FontSize=50,};
            BoxView bv = new BoxView { Color = Color.Accent, WidthRequest = 150, HeightRequest = 150, };
            RelativeLayout rl = new RelativeLayout();
            rl.Children.Add(bv, Constraint.RelativeToParent(Parent => { return Parent.Width / 2 - 75; }), Constraint.RelativeToParent(Parent => { return Parent.Height / 2 - 75; }));
            rl.Children.Add(lb, Constraint.RelativeToView(bv,(Parent,sibling) => { return sibling.X-sibling.Width; }), Constraint.RelativeToView(bv, (Parent, sibling) => { return sibling.Y-Device.GetNamedSize(NamedSize.Large,typeof(Label)); }));
            MainPage = new ContentPage
            {
                Content = rl,
            };
        }
    }
}

六、绝对布局:AbsoluteLayout

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App4
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
              //绝对布局
            var green = new Label {Text="Green Color",FontSize=20,TextColor=Color.Black,BackgroundColor=Color.Green,WidthRequest=200,HeightRequest=50 };
            var pink = new Label { Text = "Pick Color", FontSize = 20, TextColor = Color.Black, BackgroundColor = Color.Pink, WidthRequest = 200, HeightRequest = 200 };
            var yellow= new Label { Text = "Yellow Color", FontSize = 20, TextColor = Color.Black, BackgroundColor = Color.Yellow, WidthRequest =100, HeightRequest = 50 };
            AbsoluteLayout rl = new AbsoluteLayout();
            rl.Children.Add(green,new Point(50,100));
            rl.Children.Add(pink, new Point(80, 150));
            rl.Children.Add(yellow, new Point(100, 370));
            MainPage = new ContentPage
            {
                Content = rl,
            };
        }
    }
}

七、网格布局:Grid
Grid网格布局,最自由的布局方式,开发者可以在网格中指定网格数,还可以设置行、列之间的分割线,网格中可以实现跨行、跨列,相当于WebForm中的Table布局。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App5.MainPage">
   <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*">
            </RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*">
            </ColumnDefinition>
        </Grid.ColumnDefinitions>
        <BoxView Color="Red" Grid.Row="0" Grid.Column="0"></BoxView>
        <BoxView Color="Blue" Grid.Row="0" Grid.Column="1"></BoxView>
        <BoxView Color="Yellow" Grid.Row="1" Grid.Column="0"></BoxView>
        <BoxView Color="Green" Grid.Row="1" Grid.Column="1"></BoxView>
    </Grid>
</ContentPage>

第三章:页面
一、内容页面:ContentPage
二、导航页面:NavigationPage
用来管理页面之间的导航和页面堆栈的页面,会在IOS和ANDROID屏幕的顶部添加导航条,除了显示当前标题外,还有一个返回按钮,windows phone的外观和内容页面没有什么区别,点击windows phone下方的上一步按钮,会返回到调用页面。

前台文件

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App5.MainPage">
     <StackLayout>
        <Button Text="打开新页面" HeightRequest="100" Clicked="Button_Clicked">
        </Button>
    </StackLayout>

</ContentPage>

后台文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App5
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private void Button_Clicked(object sender,EventArgs e)
        {
            Navigation.PushAsync(new MainPage());
        }
        
    }
}

主程序调用方法:

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App5
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage =new NavigationPage(new MainPage());//重要,不加new NavigationPage会出错
        }
    }
}

三、主从页面:MasterDetailPage
用来管理Master和Detail页面的页面,一般用在新闻类应用中,阅读新闻时,一开始只有一个标题,当点击标题后才会有详细部分。
创建MasterDetailPage.xaml文件,系统会生成 四个文件:
MasterDetailPage1.xaml
MasterDetailPage1Detail.xaml
MasterDetailPage1Master.xaml
MasterDetailPage1MasterMenuItem.cs
在MasterDetailPage1.xaml 文件中文件头加上:MasterBehavior=“Popover”,意思是在手机端运行

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App6.MasterDetailPage1" MasterBehavior="Popover"//重要
             xmlns:pages="clr-namespace:App6">
  <MasterDetailPage.Master>
    <pages:MasterDetailPage1Master x:Name="MasterPage" />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>
        <pages:MasterDetailPage1Detail />
      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

四、标签页面:TabbedPage
TabbedPage被称为标签页面,可以在切换屏幕的情况下,通过Tab进行子页面的导航,它是在三个平台 中显示出来效果差别最大的一种页面,IOS的Tab在下方,ANDROID的在上方,windows phone的是在pivot。

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App6.TabbedPage1">
  <!--Pages can be added as references or inline-->
    <ContentPage Title="Tab 1">
        <ContentPage.Content>
            <BoxView Color="Red">
                
            </BoxView>
        </ContentPage.Content>
    </ContentPage>



    <ContentPage Title="Tab 2">
        <ContentPage.Content>
            <BoxView Color="Green">

            </BoxView>
        </ContentPage.Content>
    </ContentPage>
    <ContentPage Title="Tab 3">
        <ContentPage.Content>
            <BoxView Color="Yellow">

            </BoxView>
        </ContentPage.Content>
    </ContentPage>
</TabbedPage>

五、滑动页面:CarouselPage(已取消)
第四章:通用界面元素(通用控件)
一、显示图像:
1、显示本地图像
开发者在开发应用时,经常会使用到网络的图像资源,这样可以大大减少应用程序安装包的大小,显示网络图像首先需要使用到ImageSource的FromUri()静态方法获得一个图像来源,然后需要使用Image的Source属性对图像控件的来源进行设置,即对图像控件显示的地址内容进行设置,从而实现对图像的显示。

2、显示网络图像
Image控件除了可以显示网络图像外,还可以显示本地图像,在三个平台的应用程序中显示本地图像时需要分为两种:一种是显示相同的图像,另一种是显示不相同的图像。显示相同的图像可以使用ImageSource的FromResource()方法显示不相同的图像使用ImageSource的FromFile()方法,注意此方法在Android环境下运行不成功!原因等查!

二、定制显示的图像
1、缩放图像:Scale
2、设置图像的缩放模式:Aspect:分为三种:FIll、AspectFill、AspectFit。
Fill:图像全部显示,但是会导致图像变形
AspectFill:裁剪图像使其填满显示区域
AspectFit:保证图像比例不变,且全部显示在显示区域中,会有部分空白。
3、旋转图像:Rotation
前台文件:在前端创建一个图像控件

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App9.MainPage">

    <Image x:Name="myimage">

    </Image>

</ContentPage>

后台文件:在后端设置图像属性

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App9
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            //显示网络图像:
            //第一种方法:
            //myimage.Source = ImageSource.FromUri(new Uri("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"));
            //第二种方法:
            //myimage.Source = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";

            //显示本地图像
            //一、显示相同图像(即IOS、Android、windows phone都显示一个图像)
            //myimage.Source = ImageSource.FromResource("App9.images.bd.png");
            
            //二、显示不相同的图像(即IOS、Android、windows phone分别显示不同的图像)
            //在uwf上运行成功!在android模拟器上运行不成功
            //myimage.Source = ImageSource.FromFile("bd1.png");
            
           //根据不同平台显示不同的图像,包含了缩放、填充、旋转的方法
           switch(Device.RuntimePlatform)
            {
                case "Android":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.android.jpg");
                        //myimage.Scale = 1.5;//图像放大1.5倍
                        //myimage.Aspect = Aspect.AspectFill;//裁剪图像使其填满显示区域
                        //myimage.Aspect = Aspect.Fill;//图像全部显示,但是会导致图像变形
                        //myimage.Aspect = Aspect.AspectFit;//保证图像比例不变且全部显示在显示区域中,会有部分空白
                        myimage.Rotation = 45;//旋转45度
                        break;
                    }
                case "iOS":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.ios.jpg");
                        break;
                    }
                case "UWP":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.uwp.jpg");
                        break;
                    }
                case "macOS":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.macos.jpg");
                        break;
                    }
                case "GTK":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.gtk.jpg");
                        break;
                    }
                case "Tizen":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.tizen.jpg");
                        break;
                    }
                case "WPF":
                    {
                        myimage.Source = ImageSource.FromResource("App9.images.wpf.jpg");
                        break;
                    }

                    
            }
        }
    }
}

三、显示彩色的矩形方块
BoxView用来绘制一个具有颜色的矩形块,可以用在内置的图像或者自定义控件中,BoxVIew默认尺寸:40X40,可以使用VisualElement中的WidthRequest属性和HeightRequest。Xamarin.Forms中跨平台的颜色类Color提供了多种建立色彩实例的方法:Named Colors,FromHex,FromHsla,FromRgb,FromRgba,FromUint。

前台文件:可以直接在前端设置颜色

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App11.MainPage">

    <BoxView x:Name="mybv" Color="Red" WidthRequest="150" HeightRequest="150" HorizontalOptions="Center" VerticalOptions="Center">
        
    </BoxView>
</ContentPage>

后台文件:也可以通过后台对前端的控件设置颜色

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App11
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            mybv.Color = Color.Red;//后台设置颜色
            mybv.Color = Color.FromRgb(255, 255, 0);//后台设置颜色
        }
    }
}

四、标签控件和文本框控件
Label用来在应用程序中显示少量的文本信息,它是一个只读的文本控件,其常用属性:
Font:设置或获取标签的字体
FontAttributes:设置或获取标签是否为粗体、斜体或两者都不是
FontSize:设置或获取标签字体大小
HorizontalTextAlignment:设置或获取水平对齐方式
LineBreakMode:设置或获取内容显示的格式
Text:获取或设置文本
TextColor:获取或设置文本颜色
VerticalTextAlignment:获取或设置垂直对齐方式
XAlign:设置或获取水平对齐方式线束标签内的文本
YAlign:设置或获取垂直对齐方式约束标签内的文本

Entry控件:输入文本
Entry是一种常见的单行读写文本控件,简单说就是输入控件,最常用的莫过于登陆界面中的输入用户名和密码功能。
常用的属性:
IsPassword:设置并获取文本框中的文本是否为密码形式
Plactholder:设置并获取文本框的占位符,输入前的提示文本内容
PlaceHolderColor:设置并获取文本框的点位符颜色
Text:设置并获取文本框的文本
TextColor:设置并获取文本框中的文本颜色
常用方法:
Completed事件:用户完成输入或者按下return键后触发
TextChanged事件:在文本框中的文本发生变化时触发

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App11.MainPage">
    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
        <Label x:Name="mylb" Text="我是一个标签"></Label>
        <Entry x:Name="myey" Placeholder="请输入内容" PlaceholderColor="Red" IsPassword="True" WidthRequest="150"></Entry>
    </StackLayout>
    
</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App11
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            myey.Completed += (s, e) => { mylb.Text=((Entry)s).Text; };
            myey.TextChanged += (s, e) => { mylb.Text = ((Entry)s).Text; };
        }
    }
}

五、文本框视图Editor与键盘
文本视图Editor和文本框一样,也是输入控件,但它可以让用户输入多行,其属性与方法和文本框几乎相同,相当于WebForm中的MemoEidt控件。
键盘:
轻捭文本框或者文本视图后,弹出的就是键盘(或是虚拟键盘),它呆以实现用户输入,我们可以制定键盘类型,当要输入联系人电话号码时,键盘就应该变为数字键盘,要输入英文时键盘应该变为英文键盘,需要指定键盘的类型时,需要使用Keyboard属性,它是InputView类的属性。
键盘类型:
Default:默认键盘
Chat:可以用于短信和表情
Email:输入邮件地址的使用
Numeric:输入数字时使用。
Telephone:输入电话号码时使用
Url:输入文件客户擦头网址时使用
我们还可以制定额外的键盘选项,拼写检查、大小写、单词补全等,此时需要使用Keyboard类的Create()方法,此方法接受一个KeyboardFlags枚举,此枚举存放的就是键盘的额外选项,CapitalizeSentence:句子的第一个单词首字母大写。
Spellcheck:拼写检查。
Suggestions:单词补全
All:提供所有额外功能

键盘的用法:前台的写法,注意Keyboard。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App12.MainPage">

    <StackLayout>
        <Editor  x:Name="myeditor"  Keyboard="Default"  ></Editor>
    </StackLayout>

</ContentPage>

后台的写法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App12
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            myeditor.Keyboard = Keyboard.Numeric;//重要
        }
    }
}

六、按钮控件
Button控件大家都很熟悉了,设置其外观:
BorderColor:设置或获取边框的颜色
BorderRadius:设置或获取圆角
BorderWidth:设置或获取边框宽度
ImageSource:设置或获取显示的图像,作为按钮的显示内容
Text:设置或获取按钮显示的文本
TextColor:设置或获取按钮的文本颜色
Button交互:Clicked事件

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout>
        <--注意:在试验过程中,前台对ImageSource属性的设置,直接引用文件名,但是要将图片放在App13.Android.Resource.drawable中才可以的哦!否则不显示图片,如:<Button x:Name="mybt" Text="点击我" ImageSource="bd.png"></Button>,后台设置见下面的代码 -->
        <Button x:Name="mybt" Text="点击我" VerticalOptions="Center" HorizontalOptions="Center" WidthRequest="150" CornerRadius="20" HeightRequest="50" Clicked="mybt_Clicked">
        </Button>
    </StackLayout>

</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void mybt_Clicked(object sender, EventArgs e)
        {
           Button bt=((Button)sender);
            bt.WidthRequest = 200;
            bt.HeightRequest = 231;
            bt.ImageSource = ImageSource.FromResource("App13.bd.png");
           

        }
    }
}

七、开关控件
Switch开关控件常用来控制某个功能的开关状态,如蓝牙、GPS、WiFi信号等,Switch属性IsToggled用来设置或获取开关的状态,Toggled事件用来实现开关控件的交互,此事件在开关事件被触发时调用。
前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
       
        <Switch x:Name="mysw" Toggled="mysw_Toggled">
        </Switch>
    </StackLayout>

</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

       

        private void mysw_Toggled(object sender, ToggledEventArgs e)
        {
            if(mysw.IsToggled)
            {
                st.BackgroundColor = Color.Red;
            }
            else
            {
                st.BackgroundColor = Color.Yellow;
            }
        }
    }
}

八、滑块控件
Slider滑块控件可以从一个连续的区间中选择一个值 ,例如:可以用来控制设备的当前音量、亮度等等,开发者使用Slider控件的3个属性来对slider进行设置。

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
        <Label x:Name="mylbl"></Label>
        <Slider x:Name="sd" Maximum="100" Minimum="0" Value="0" ValueChanged="sd_ValueChanged"></Slider>
    </StackLayout>

</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

      

        private void sd_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            var sl = (Slider)sender;
            mylbl.Text = sl.Value.ToString();
        }
    }
}

九、步进控件
Stepper步进控件是一个用来输入数字的控件,它类似于开关控件,但它有“+”和“-”两个按钮,这两个按钮共同控制同一个Value的增减,Stepper常用属性如下:
Increment:设置或获取步进制件的步长
Maximun:设置或获取步进控件的最大边界值
Mininum:设置或获取步进控件的最小边界值
Value:设置或获取步进控件的当前值
Stepper的交互通过其事件,ValueChanged来实现,此事件在步进控件当前的值 发生改变时触发。

后台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
        <Label x:Name="mylbl"></Label>
        <Stepper x:Name="sd" Maximum="100" Minimum="0" Value="50" Increment="1" ValueChanged="sd_ValueChanged"></Stepper>
    </StackLayout>

</ContentPage>

前台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

      

        private void sd_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            var sl = (Stepper)sender;
            mylbl.Text = sl.Value.ToString();
        }
    }
}

十、进度条和指示器

ProgressBar进度条控件类似于一个温度计,生动地展示了进度,通常用来代表一个耗时的操作,其完成的百分比是可以计算的,例如迅雷中用进度条来告诉用户下载的进度,进度 条控件的Progress属性可以用来设置或获取当前的进度值。
ProgressTo()方法可以高瞻远瞩进度条以动画的形式到达某一进度上。
语法:
ProgressTo(Double value,Uint32 length,Easing easing)
value:指定动画持续时间,以ms为单位
length:指定需要达到的进度
easing:指定动画的相对速度

ActivityIndicator指示器控件可以告知用户有一个操作正在进行,在应用唾弃中使用可以消除用户等待的心里事件,增加用户的体验,常用属性是Color(设置阿卡获取指示器的颜色),IsRunning(设置或获取指示器是否正在进行)。
后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private void Button_Clicked(object sender, EventArgs e)
        {
            if (myb.Text == "start")
            {
                myb.Text = "end";
                myp.ProgressTo(1, 1000, Easing.Linear);
                mya.IsRunning = true;
            }
            else
            {
                myp.Progress = 0.1;
                myb.Text = "start";
                mya.IsRunning = false;
            }
        }
    }
}

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
        <ProgressBar x:Name="myp" Progress="0.1"></ProgressBar>
        <ActivityIndicator x:Name="mya"></ActivityIndicator>
        <Button x:Name="myb" Text="start" Clicked="Button_Clicked"></Button>
      
    </StackLayout>

</ContentPage>

十一、警告视图
类似于winform中的MessageBox的作用。
有两种:1、DisplayAlert(string title,string message,string cancel)
2、DisplayAlert(string title,string message,string accept,string cancel)
后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }


        //注意:一个按钮时用这个,修饰符不同,如果用await时必须是异步执行的,要加async关键字来修饰
        //private void myb_Clicked(object sender, EventArgs e)
        //{
        //   var alert = DisplayAlert("友情提示", "到点了!该下班了!", "知道了");

        //}


        //注意:一个按钮时用这个,修饰符不同,如果用await时必须是异步执行的,要加async关键字来修饰
        async void myb_Clicked(object sender, EventArgs e)
        {
          
            var alert2 = await DisplayAlert("友情提示", "到点了!该下班了!", "yes", "no");
            if (alert2)
            {
                this.BackgroundColor = Color.Red;
            }
            else
            {
                this.BackgroundColor = Color.White;
            }
        }
    }
}

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
      
        <Button x:Name="myb" Text="显示提醒" Clicked="myb_Clicked"></Button>
      
    </StackLayout>

</ContentPage>

十二、操作表视图(警告视图)

操作表也是一个警告视图的一种,只是可以设置多个按钮且可以根据选择执行不同的结果。
语法:
DisplayActionSheet(string title,string cancel,string destraction,string buttons)
title:是一个字符串,用来表示操作表的标题,不为空
cacel:是一个字符串,用来表示“cancel"标题,为空是表示隐藏、取消行动。
destraction:是一个字符串,用来显示”Destract"按钮,可以为空。
buttons:表示额外按钮的文本标签,不可为空。

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
      
        <Button x:Name="myb" Text="显示提醒" Clicked="myb_Clicked"></Button>
      
    </StackLayout>

</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        //注意:如果用await时必须是异步执行的,要加async关键字来修饰
        async void myb_Clicked(object sender, EventArgs e)
        {
            var dd = await this.DisplayActionSheet("设置背景颜色", "Cancel", "Red", "Blue", "Green");
            if(dd=="Red")
            {
                this.BackgroundColor = Color.Red;
            }
            else if(dd == "Blue")
            {
                this.BackgroundColor = Color.Blue;
            }
            else if(dd == "Green")
            {
                this.BackgroundColor = Color.Green;
            }
        }
    }
}

十四、自定义界面元素
前台文件对自定义按钮的使用方法:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:app13="clr-namespace:App13"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">

        <app13:Mybutton Text="自定义按钮"></app13:Mybutton>
        
    </StackLayout>

</ContentPage>

后台文件:自定义按钮类

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace App13
{
     class Mybutton:Button
    {
       public Mybutton()
        {
            BackgroundColor = Color.Red;
            TextColor = Color.White;
            BorderColor = Color.Black;
            BorderWidth = 50;
            CornerRadius = 20;
        }
    }
}

第五章:表视图
一、表视图
TableView表视图是一个带滚动条的数据列表,而且行的样式可以不同,表视图的使用场景:
1、呈现一个设置列表
2、显示一个表单中的数据集合
3、显示数据,要求行的样式不同
表视图的结构:

前端文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:app13="clr-namespace:App13"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
        <TableView Intent="Settings">
            <TableRoot Title="设置">
                <TableSection Title="网络设置">
                    <SwitchCell Text="WiFi设置" OnChanged="SwitchCell_OnChanged"></SwitchCell>
                    <SwitchCell Text="询问是否加入网络"></SwitchCell>
                </TableSection>
                <TableSection Title="隐私设置">
                    <SwitchCell Text="定位服务"></SwitchCell>
                    <SwitchCell Text="其他服务"></SwitchCell>
                </TableSection>
            </TableRoot>
        </TableView>
        
    </StackLayout>

</ContentPage>

后端文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using App13;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        //后台事件
        private void SwitchCell_OnChanged(object sender, ToggledEventArgs e)
        {
            DisplayAlert("信息提示","WiFi已开启!", "知道咧!");
        }
    }
}

其中在表视图中首先需要有一个TableRoot作为根节点,在根节点中需要有一个或多个TableSection节点,在TableSection节点中又包含了一个或多个显示元素,Intent属性有四个值:Data、Form、Menu、Settings。
Data:用于显示数据输入
Form:用于操作对象
Menu:用作显示一个菜单选项
Settings:用于显示一个配置设置列表
4、表视图的填充:要对表视图的内容进行填充,就要使用到单元格,内置的四种单元格分别为:
SwitchCell:
EntryCell:
TextCell:
ImageCell:
如果内置的单元格不能满足要求,可以自定义单元格,使用ViewCell类。

自定义单元格:直接在后台代码生成

项目主程序后台文件:app13.xaml.cs代码

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App13
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new ContentPage
            {
                Content = new TableView
                {
                    Intent = TableIntent.Form,
                    Root = new TableRoot("生日表格")
                    {
                        new TableSection{
                          KeyValueCell("张三","2010-07-01"),
                          KeyValueCell("李四", "2010-08-01"),
                           KeyValueCell("王五","2010-09-01"),
                          KeyValueCell("赵六", "2010-10-01")
                        }
                    }

                }
            };
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
        public Cell KeyValueCell(string name, string date)
        {
            var customCell = new ViewCell
            {
                View = new StackLayout
                {
                    Children =
                    {
                        new Label{Text=name},
                        new Label{Text=date,TextColor=Color.Red}
                    }
                }
            };
            return customCell;
        }
    }
}

----TableView视图的添加行与删除行-----

后台代码:

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App14
{
    public partial class App : Application
    {
        TableSection tableSection;
        public App()
        {
            InitializeComponent();
             //定义TextCell
            var textCell = new TextCell
            {
                Text = "TextCell 文本内容",
                Detail = "TextCell 细节内容"
            };
            //定义EntryCell
            var entryCell = new EntryCell
            {
                Label = "EntryCell标题",
                Placeholder = "default keyboard",
                Keyboard = Keyboard.Default
            };
           
            //定义MenuItem
            var addAction = new MenuItem {Text="插入操作" };
            addAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
            //为textCell添加菜单
            textCell.ContextActions.Add(addAction);
            //为addAction绑定单件事件
            addAction.Clicked += AddAction_Clicked;
          
            // 定义TableSection
            tableSection = new TableSection("Selection第一行标题")
            {
                textCell,entryCell
            };
           
           //定义TableView
            var tableView = new TableView
            {
                Intent = TableIntent.Settings,
                Root = new TableRoot("表视图标题")
                {
                    tableSection
                }
           };

            //定义按钮及事件
            Button btn = new Button
            {
                Text="删除一行"
            };
            btn.Clicked += Btn_Clicked;
           
            //定义StackLayout
            StackLayout sl = new StackLayout();
            sl.VerticalOptions = LayoutOptions.Center;
            sl.HorizontalOptions = LayoutOptions.Center;
            //向sl中添加元素tableView和btn
            sl.Children.Add(tableView);
            sl.Children.Add(btn);
            //定义主页
            MainPage = new ContentPage
            {
                Content = sl
            };
          
        }

        private void Btn_Clicked(object sender, EventArgs e)
        {
            if (tableSection.Count > 0)
            {
                tableSection.RemoveAt(0);
            }
        }

        private void AddAction_Clicked(object sender, EventArgs e)
        {
            var switchCell = new SwitchCell
            {
                Text="开关单元格",On=true
            };
            tableSection.Add(switchCell);
        

        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}

在这里插入图片描述

二、列表视图:ListView
1、ListView列表视图用于显示数据列表(这些数据可是人、电话号码、短信、问题或者其他任何东西),一般在内容较长时需要滚动显示的时候用到,列表视图的填充分为两种:
A、普通列表视图的内容填充:
1)填充字符串数组
2)填充复杂的集合
A)文本单元格
B)图像单元格
C)自定义单元格
B、分组列表视图的内容填充
2、定制列表视图的外观
A、行高:列表中每一行内容的字体的高度大于表中行的调试时,显示的内容就会影响美观,而且显示的只有部分内容,此刻要设置行高RowHeight来解决,TableView中也通用。
B、页眉面脚:页眉、页脚显示文档的附加信息,常用来插入时间、日期、页码、单位名称等,页眉还可以实现添加文档注释等内容的功能。添加页眉使用ListView的Heaer属性,添加页脚使用Footer属性。
C、分割线:显示在每个单元格之间,IOS和Android存在分割线并且可以设置隐藏的,此刻需要设置SeparatorVisibilty属性,而WindowsPhone设有分割线。
3、操作表
A、选择行:ListView中有两个专门用来实现选择行的事件;一个为ItemSelected事件,另一个为:ItemTapped事件。
B、下拉刷新:ListView中专门提供了下拉刷新的属性以及方法,如:IsRefreshing属性,设置或获取ListView列表是否正在刷新,RefreshCommand属性设置或获取ListView列表视图进入刷新状态运行的命令。BeginRefresh()方法,进入刷新状态,EndRefresh()方法结束刷新状态,Refreshing事件在ListView列表视图刷新时调用。
C、添加行:需要使用到Cell类的ContextAction属性,该属性可以获取菜单项列表,在此列表中显示了用户可以执行的操作。
D、删除行:与添加行实现的一样,需要使用Cell类的ContextAction属性。

----------普通列表视图:填充字符串数组的实现代码:---------

前台文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:app13="clr-namespace:App13"
             x:Class="App13.MainPage">

    <StackLayout x:Name="st">
        <ListView x:Name="myl" VerticalOptions="Center" HorizontalOptions="Center">
            
        </ListView>
        
    </StackLayout>

</ContentPage>

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using App13;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            myl.ItemsSource = new string[] {"张三","李四","王五","赵六","冯七","胡八" };

        }
   
    }
}

-------普通列表视图:填充复杂的集合---------

后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using App13;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            //填充字符串数组
            //myl.ItemsSource = new string[] {"张三","李四","王五","赵六","冯七","胡八" };

            //填充复杂的集合
            var cities = new List<city>()
            {
                new city{Name="张三",State="济南市"},
                new city{Name="李四",State="南京市"},
                new city{Name="王五",State="上海市"},
                new city{Name="赵六",State="南京市"},
                new city{Name="冯七",State="淄博市"},
                new city{Name="胡八",State="潍坊市"}


            };
            //创建数据模板
            DataTemplate dataTemplate = new DataTemplate(typeof(TextCell));
            dataTemplate.SetBinding(TextCell.TextProperty,"Name");
            dataTemplate.SetBinding(TextCell.DetailProperty, "State");
            
            //设置ListView的ItemTemplate,如不设置则不能正常显示文本内容
            myl.ItemTemplate = dataTemplate;
            
            //配置ItemSource
            myl.ItemsSource = cities;

        }
   
    }
}

创建city类

using System;
using System.Collections.Generic;
using System.Text;

namespace App13
{
    public class city
    {
        public string Name {get; set; }
        public  string State{get; set; }
    }
}

-----分组列表视图的填充---------
后台文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using App13;

namespace App13
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
          
            var state = new List<State>()
            {
                new State("济南地区")
                {
                    new city{Name="张先生" },
                    new city{Name="李先生"}
                },
                new State("南京地区")
                {
                    new city{Name="王先生" },
                    new city{Name="赵先生"}
                },
                new State("上海地区")
                {
                    new city{Name="胡先生" },
                    new city{Name="桑先生"}
                },
                new State("福建地区")
                {
                    new city{Name="魏先生" },
                    new city{Name="朱先生"}
                }


            };
            DataTemplate dataTemplate = new DataTemplate(typeof(TextCell));
            dataTemplate.SetBinding(TextCell.TextProperty, "Name");
            dataTemplate.SetBinding(TextCell.DetailProperty, "State");
            myl.IsGroupingEnabled = true;
            myl.GroupDisplayBinding = new Binding("Name");
            myl.GroupShortNameBinding = new Binding("Name");
            myl.ItemTemplate = dataTemplate;
            myl.ItemsSource = state;

        }

    }
}

支持分组的city类:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App13
{
    public class city
    {
        public string Name {get; set; }
      
    }
    public class State:ObservableCollection<city>
    {
        public State(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
    }
}

运行结果:
在这里插入图片描述
--------定制列表视图的外观---------
分别设置:行高、页眉、页脚、分割线(仅适用于Android和Ios)

    myl.RowHeight = 50;
    myl.Header = "运行商分类";
    myl.Footer = "查询日期:"+DateTime.Today.ToString();
    myl.SeparatorVisibility = 0;
    myl.SeparatorColor = Color.Red;

行选择事件代码:
在前端设置ItemSelected事件

   private void myl_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            DisplayAlert("友情提示", "您已选择了:" + e.SelectedItem.ToString(),"知道咧!");
        }

轻拍事件代码:
在前端设置ItemTapped事件

 private void myl_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        DisplayAlert("友情提示", "您已选择了:" + e.Item.ToString(), "知道咧!");
    }

刷新下拉列表代码:
注意:首先要将设置:myl.IsPullToRefreshEnabled = true;这是必须设置的,否则不支持下拉列表刷新功能。然后在前端设置Refreshing事件

  private void myl_Refreshing(object sender, EventArgs e)
        {
            myl.ItemsSource = new string[] { "张1", "李2", "王3", "赵4", "冯5", "胡6" };
            myl.EndRefresh();
        }
Xamarin.Android 中的网格布局(Grid Layout)是一种强大的二维布局管理器,用于创建复杂的网格结构,其中每个单元格都可以放置一个控件。网格布局可以处理行和列,并允许对单元格进行大小调整、对齐和间距设置。在 Xamarin.Forms 中,使用 Grid 类来定义网格。 网格布局的事件主要包括以下几种: 1. ItemTapped:当用户点击网格中的某个单元格时触发,这个事件通常绑定到 `Grid.ItemTapped` 或 `Cell.Tapped` 属性,可以用来执行相应的操作,例如跳转到详细页面或显示信息。 2. RowUpdated 和 ColumnUpdated:当网格的行或列发生变化(如添加、删除或移动行/列)时触发,这些事件可以帮助你在布局更新时进行必要的处理。 3. ItemSelected:在 Android 版本中,对于 `Xamarin.Forms.Grid`,并没有直接的 `ItemSelected` 事件,但你可以通过监听 `Cell.BindingContext` 的改变来间接实现类似的功能,比如在单元格被选中时更新状态。 4. LayoutChanged:当网格布局的整体大小或形状发生改变时(例如,由于父视图的尺寸变化),该事件会被触发。你可以在此事件中重新布局内部元素。 要使用这些事件,你需要将它们绑定到你的视图模型或者对应的 View 层级中,然后在事件处理器中编写响应的业务逻辑。下面是绑定和处理事件的基本步骤: ```csharp // 在 XAML 中绑定 ItemTapped 事件 <Grid.ItemTapped> <CommandParameterBinding TargetType="YourViewModel" Command="{Binding YourCommand}" ParameterPath="Item" /> </Grid.ItemTapped> // 在代码背后处理 ItemTapped 事件 public class YourViewModel : INotifyPropertyChanged { public Command YourCommand { get; } // ... private void OnItemTapped(object sender, ItemTappedEventArgs e) { var item = e.Item; // 执行相关操作 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值