第六章:按钮点击(3)

本文介绍了一个使用匿名lambda函数作为事件处理程序的示例程序ButtonLambdasPage。该程序包含一个显示数字的标签及两个按钮,一个用于使数字翻倍,另一个用于将数字减半。文章详细展示了如何在构造函数中定义这些事件处理程序并访问局部变量。

匿名事件处理程序
与任何事件处理程序一样,您可以将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函数的缺点是它们不能在多个视图中共享。 (其实他们可以,但涉及一些混乱的反射代码。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值