Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6514863
  • 博文数量: 915
  • 博客积分: 17977
  • 博客等级: 上将
  • 技术积分: 8846
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-26 09:59
个人简介

一个好老好老的老程序员了。

文章分类

全部博文(915)

文章存档

2022年(9)

2021年(13)

2020年(10)

2019年(40)

2018年(88)

2017年(130)

2015年(5)

2014年(12)

2013年(41)

2012年(36)

2011年(272)

2010年(1)

2009年(53)

2008年(65)

2007年(47)

2006年(81)

2005年(12)

分类: Android平台

2018-06-17 22:09:56

匿名事件处理程序
与任何事件处理程序一样,您可以将Clicked处理程序定义为匿名lambda函数。 这是一个名为ButtonLambdas的程序,它有一个显示数字和两个按钮的标签。 一个按钮使数字加倍,另一个减半。 通常,数字和标签变量将被保存为字段。 但是因为在定义了这些变量之后,匿名事件处理程序在构造函数中被正确定义,所以事件处理程序可以访问这些局部变量:

public class ButtonLambdasPage : ContentPage
{
    public ButtonLambdasPage()
    {
        // Number to manipulate.
        double number = 1;
        // Create the Label for display.
        Label label = new Label
        {
            Text = number.ToString(),
            FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };
        // Create the first Button and attach Clicked handler.
        Button timesButton = new Button
        {
            Text = "Double",
            FontSize = Device.GetNamedSize(NamedSize.Large,  typeof(Button)),
            HorizontalOptions = LayoutOptions.CenterAndExpand
        };
        timesButton.Clicked += (sender, args) =>
        {
            number *= 2;
            label.Text = number.ToString();
        };
        // Create the second Button and attach Clicked handler.
        Button divideButton = new Button
        {
            Text = "Half",
            FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Button)),
            HorizontalOptions = LayoutOptions.CenterAndExpand
        };
        divideButton.Clicked += (sender, args) =>
        {
            number /= 2;
            label.Text = number.ToString();
        };
        // Assemble the page.
        this.Content = new StackLayout
        {
            Children =
            {
                label,
                new StackLayout
                {
                    Orientation = StackOrientation.Horizontal,
                    VerticalOptions = LayoutOptions.CenterAndExpand,
                    Children =
                    {
                        timesButton,
                        divideButton
                     }
                 }
             }
         };
     }
}

注意使用Device.GetNamedSize为Label和Button获取大文本。 当与Label一起使用时,GetNamedSize的第二个参数应该指示一个标签,并且当与Button一起使用时,它应该指示一个Button。 这两个元素的大小可能不同。
像以前的程序一样,这两个按钮共享一个水平的StackLayout:
201806172201590339
将事件处理程序定义为匿名lambda函数的缺点是它们不能在多个视图中共享。 (其实他们可以,但涉及一些混乱的反射代码。)

阅读(2003) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~