Reputation: 181
I Am trying to create a dummy app that has multiple "Branding Packages". I have read that using a control template is the easiest way to apply a global styling to the app. most controls in the app will be added dynamically via the code behind.
However whenever I set the content view to use the control template none of the controls I have added via code will display
Here is the App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestWebApp.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="Template">
<Grid>
<Label Text="Control Template Demo App"
TextColor="White">
</Label>
<ContentPresenter/>
<BoxView Color="Teal" />
<Label Text="(c) WTF 2018"
TextColor="White"
VerticalOptions="Center"/>
</Grid>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
Here is the MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TestWebApp"
x:Class="TestWebApp.MainPage">
<ContentView ControlTemplate="{StaticResource Template}">
<ScrollView>
<StackLayout Orientation="Vertical" x:Name="MenuLayout">
</StackLayout>
</ScrollView>
</ContentView>
</ContentPage>
And here is the MainPage.xaml.cs
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace TestWebApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
List<Object> testList = TestMethod();
foreach(Object testObject in testList)
{
MenuLayout.Children.Add((View)testObject);
}
}
public List<Object> TestMethod()
{
Button newButton = new Button {Text = "This is a Test Button", BackgroundColor = Color.White};
List<Object> returnList = new List<object>();
returnList.Add(newButton);
return returnList;
}
}
}
Is there a way to dynamically create a page from the code behind while still implementing the control template
Upvotes: 1
Views: 231
Reputation: 169160
Try to add some RowDefinitions
to the Grid
in the template:
<ControlTemplate x:Key="Template">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Text="Control Template Demo App" TextColor="White" />
<ContentPresenter Grid.Row="1" />
<BoxView Color="Teal" Grid.Row="2" />
<Label Text="(c) WTF 2018" TextColor="White" VerticalOptions="Center" Grid.Row="3"/>
</Grid>
</ControlTemplate>
Upvotes: 1