简体   繁体   中英

Does anyone know how I can create a CollectionInitializer for a StackLayout?

Currently I am doing this:

CustomFrame = new StackLayout()
{
    Children =
    {
        new EmptyGrid(),
        new ContentLine(),
    }
}

What I would like to be able to do is to have a special kind of StackLayout so I can do this this:

CustomFrame = new SimpleStackLayout()
{
    new EmptyGrid(),
    new ContentLine(),
}

The documentation states:

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method.

We should therefore be able to create a derived class that implements this Add method and the required IEnumerable :

public class SimpleStackLayout : StackLayout, IEnumerable<View>
{
    public void Add(View view)
    {
        this.Children.Add(view);
    }

    public IEnumerator<View> GetEnumerator()
    {
        return this.Children.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.Children.GetEnumerator();
    }
}

You can now initialize it as you desire:

CustomFrame = new SimpleStackLayout()
{
    new EmptyGrid(),
    new ContentLine(),
}

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