C# ControlTemplate覆盖以编程方式添加的控件
我正在尝试创建一个虚拟应用程序,它有多个“品牌包”。 我读过,使用控件模板是将全局样式应用于应用程序的最简单方法。应用程序中的大多数控件将通过代码隐藏动态添加 但是,每当我将内容视图设置为使用控件模板时,我通过代码添加的控件都不会显示 这是App.xamlC# ControlTemplate覆盖以编程方式添加的控件,c#,xamarin.forms,C#,Xamarin.forms,我正在尝试创建一个虚拟应用程序,它有多个“品牌包”。 我读过,使用控件模板是将全局样式应用于应用程序的最简单方法。应用程序中的大多数控件将通过代码隐藏动态添加 但是,每当我将内容视图设置为使用控件模板时,我通过代码添加的控件都不会显示 这是App.xaml <?xml version="1.0" encoding="utf-8" ?> <Application xmlns="http://xamarin.com/schemas/2014/forms"
<?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>
这是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>
这是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;
}
}
}
使用系统;
使用System.Collections.Generic;
使用Xamarin.Forms;
命名空间TestWebApp
{
公共部分类主页:ContentPage
{
公共主页()
{
初始化组件();
List testList=TestMethod();
foreach(testList中的对象testObject)
{
MenuLayout.Children.Add((视图)testObject);
}
}
公共列表TestMethod()
{
按钮newButton=newButton{Text=“这是一个测试按钮”,BackgroundColor=Color.White};
List returnList=新列表();
返回列表。添加(新按钮);
退货清单;
}
}
}
是否有一种方法可以在执行控制模板的同时从代码隐藏动态创建页面尝试将一些
行定义
添加到模板中的网格
:
<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>
从“代码”中,您希望将按钮添加到StackLayout。请尝试此操作。()这确实解决了问题。我现在只需要正确设置控件模板的格式,以用作全局样式表