Reputation: 5968
I'm trying to create some custom controls for Xamarin forms...
The controls should behave as a group of other controls. For example Label + Entry as one control to be inserted in a page.
I created a simple control here inherting from the class View.
This is an example of class with two labels. And inside this class, other controls are supposed to be inserted in addition to these labels.
public class Ton : View
{
public Ton() : base()
{
Label L;
L = new Label();
L.Parent = this;
L.Text = "XXX";
Label M;
M = new Label();
M.Parent = this;
M.Text = "YYY";
}
}
I insert then this class in a page :
<local:Ton></local:Ton>
but the contol is not shown in the page.
Does anyone know the reason please ?
Thanks. Cheers,
Upvotes: 0
Views: 161
Reputation: 89179
you create two Labels but don't actually add them to the View hierarchy
public class Ton : ContentView
{
public Ton() : base()
{
Label L;
L = new Label();
L.Text = "XXX";
Label M;
M = new Label();
M.Text = "YYY";
// because you have multiple elements, they must be contained in a Layout
var stack = new StackLayout();
stack.Children.Add(L);
stack.Children.Add(M);
// assign your controls to the View hierarchy
this.Content = stack;
}
}
Upvotes: 2
Reputation: 1474
A view is an abstract class and it cannot not have children. Also it does not know how to layout it's children inside it. You must have inherited your class from Layout<View>
or someother existing layout classes like Grid
, StackLayout
, RelativeLayout
, etc..
The base class depends on how you need to layout your children.
Refer my below GitHub repository to know how to create a custom control. https://github.com/harikrishnann/BusyButton-XamarinForms
Upvotes: 2