简体   繁体   中英

How a code with the lamda expression on construction of a entity works

What is the meaning of the below code,

var personDataTemplate = new DataTemplate(() =>
    {
        var grid = new Grid();
        ...
        var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
        var ageLabel = new Label();
        var locationLabel = new Label { HorizontalTextAlignment = TextAlignment.End };

        nameLabel.SetBinding(Label.TextProperty, "Name");
        ageLabel.SetBinding(Label.TextProperty, "Age");
        locationLabel.SetBinding(Label.TextProperty, "Location");

        grid.Children.Add(nameLabel);
        grid.Children.Add(ageLabel, 1, 0);
        grid.Children.Add(locationLabel, 2, 0);

        return new ViewCell { View = grid };
    });

How the code runs with the below instance,

new DataTemplate(() => { --- How the code runs here --- })

Is it like a self invoking function?

DataTemplate's constructor has a parameter that takes a delegate, probably something like

public DataTemplate(Func<ViewCell> foo)

By calling () => {} you define anonymous method(lambda expression).

Inside DataTemplate it is called somewhere like this:

ViewCell bar = foo();

You can use it to allow users to define their own instance of ViewCell that should be used inside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM