【发布时间】:2017-03-11 16:32:01
【问题描述】:
我正在尝试在 Xamarin 表单中创建一个 XAML 模板,我可以从多个屏幕引用该模板。该模板有一个标题、一个摘要,并且可以接收触摸输入。在附加的线框中,将有一个模型支持三个数据块。我已经阅读了https://developer.xamarin.com/guides/xamarin-forms/templates/control-templates/template-binding/ 的文档,但在这一点上,我觉得我错过了一个重要的概念。我想我只需要创建一个 ContentView 模板,并以某种方式使里面的标签在运行时通过 .BindingContext 绑定到一个对象。我错过了什么?
内容页面
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Namespace.SettingsPage"
Title ="Settings">
<ContentPage.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="SettingTemplate">
<StackLayout>
<Label
x:Name="Header"
Text="{TemplateBinding Parent.Header}" />
<Label
x:Name="Summary"
Text="{TemplateBinding Parent.Summary}"/>
</StackLayout>
</ControlTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<StackLayout>
<ContentView x:Name="alerts" ControlTemplate="{StaticResource SettingTemplate}"></ContentView>
<ContentView x:Name="recipients" ControlTemplate="{StaticResource SettingTemplate}"></ContentView>
<ContentView x:Name="log" ControlTemplate="{StaticResource SettingTemplate}"></ContentView>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
代码隐藏
using Xamarin.Forms;
namespace Namespace.Settings
{
public partial class SettingsPage : ContentPage
{
protected SettingsViewModel viewModel;
public SettingsPage(AlertInfo info)
{
InitializeComponent();
BindingContext = viewModel = new SettingsViewModel(info, this);
// Bind individual models here. AlertSummary VM has logic to pull out
// header and summary fiels.
this.alerts.BindingContext = new AlertSummaryViewModel(info, Summary.ALERTS, this);
this.recipients.BindingContext = new AlertSummaryViewModel(info, Summary.RECIPIENTS, this);
}
}
}
【问题讨论】:
-
问题不清楚。你到底想做什么但不起作用?例如,这是我的页面,这是我要基于该模板添加的控件,但我没有看到。另外请提供所有必要的xml和代码来重现
-
谢谢 Yuri,我在后面添加了 xaml 和代码。
-
重现缺少的定义:SettingsViewModel、AlertInfo、AlertSummaryViewModel、Summary.ALERTS。提供这些后,请告诉我什么不起作用?从图像中我看到所有数据都已填充或者是所需的图像?
-
这是一个预期结果的线框图。我不是在寻找调试,而是寻找有关 Xamarin Forms 是否可以实现这一点的指导,如果可以,在哪里寻找示例。
-
您在问题的链接中提供了可能的示例。如果你把所有事情都做对了,你就会完成它。如果您有问题,请提供代码以快速重新创建并帮助您解决问题。我什至不知道你在屏幕上看到了什么,有什么问题
标签: xamarin.forms