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: