A stylesheet pattern for UI

I’ve settled on a pattern for creating child UI elements and I thought I would share it. I like it because it supports a cascading-style-sheet type approach and saves code by reducing repeated code.

So, start with a delegate like this (I defined all this in a base class for all my UI classes, which is why you will see ‘protected’) :

protected delegate void ButtonInitDelegate(Text label, Button textbox);

And a creation function like this:

protected virtual UIElement CreateButton(string label, ButtonInitDelegate initFn = null)
    var txt = new Text(this.Frame.HeadingFont, label)
        VerticalAlignment = VerticalAlignment.Center,
        HorizontalAlignment = HorizontalAlignment.Center,

    var button = new Button()
        Child = txt,
        Width = 100,
        Height = 50,
    initFn?.Invoke(txt, button);

    return button;

Then you can use it in a child page like this:

    ButtonInitDelegate styleForButtons = (label, button) =>
        button.Width = 200;
        button.Height = 60;
        button.SetMargin(50, 10, 50, 10);

    leftStack.Children.Add(CreateButton("Network", (label, button) =>
        button.Click += this.Network_Click;
        styleForButtons(label, button);

    leftStack.Children.Add(CreateButton("Display", (label, button) =>
        button.Click += this.Display_Click;
        styleForButtons(label, button);

When you make the observation that ‘styleForButtons’ could call another ‘parent’ lambda, then boom - you’ve got cascading styles, easier editing, and a reduction in code footprint.

The above layout, in context, resulted in the buttons you see here:


please share an complete example (on github) …

@valon_hoti_gmail_com - eventually, I will separate out the page-based navigation model (mobile-style navigation stack), and I will provide that as a nuget, and then I can publish a full example. For now, you can use the snippets above in any program that uses TinyCLR’s UI library.

Currently, the code you want is too tangled up with my actual app functionality, but maybe I can water it down to just network settings and a few other example pages.

There are a few other things I can nuget’ize out of this app. A demo video will probably pop up this weekend.

Actually, because the page-based nav code mirrors the UWP (and Xamarin) nav models, perhaps GHI might add it as another lib in their TinyCLR Libraries project. I’d be happy to sign it over to them for that purpose.