【发布时间】:2021-12-31 01:33:20
【问题描述】:
我不知道标题是否足够清楚,所以让我解释一下我要做什么:
我有一个LoggingField 类,它由以下内容组成:
XAML:
<ContentView.Content>
<StackLayout>
<Label Style="{DynamicResource LabelTitle}" x:Name="LabelTitle"/>
<View x:Name="FieldContent"/>
</StackLayout>
</ContentView.Content>
C#:
[ContentProperty(nameof(Field))]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoggingField : ContentView
{
/// <summary>
/// Creates a new Logging field.
/// </summary>
public LoggingField()
{
InitializeComponent();
}
//
// PUBLIC
//
// PROPERTIES
/// <summary>
/// The field's content.
/// </summary>
public View Field
{
set => FieldContent = value;
get => FieldContent;
}
/// <summary>
/// The field's title.
/// </summary>
public string Text
{
set => LabelTitle.Text = value;
get => LabelTitle.Text;
}
}
页面 XAML:
<logcontent:LoggingField Text="Test Title:">
<Entry Placeholder="PlaceholderText"/>
</logcontent:LoggingField>
从中,您可以看到我希望<Entry Placeholder="PlaceholderText"/> 覆盖<View x:Name="FieldContent"/> 对象,但我无法使其工作。它总是会覆盖整个 ContentView,只显示占位符 Entry。
我所做的唯一改进是在 ContentView 的 C# 类中添加了[ContentProperty(nameof(Field))],这使得它的原始内容可以显示,但Entry 对象将不再出现。
那么我怎样才能让Entry 对象正确覆盖ContentView 中的View 对象呢?提前致谢。
PS:我尝试将<View x:Name="FieldContent"/> 替换为<ContentPresenter x:Name="FieldContent"/> 并改用ContentPresenter.Content,但无济于事。
【问题讨论】:
-
首先,去掉
[ContentProperty...]属性——在一个ContentView中,整个内容就是ContentProperty;您绝对不希望 Field 成为那样;这将覆盖您的整个 StackLayout。在链接的答案中,请注意<ContentView x:Name="contentView" ... ControlTemplate="{StaticResource TealTemplate}">That 声明使用ControlTemplate。然后定义该模板,如链接答案所示。 -
@ToolmakerSteve 这正是我所需要的,谢谢!但是,是否可以让
ContentView对象从代码而不是 XAML 中获得所需的ContentTemplate?我看到ControlTemplate={StaticResource TargetControlTemplate}行在该类型的每个实例中重复,所以我想知道是否可以将对象的ControlTemplate属性默认为一个值。 -
我不确定我是否理解这个问题。每当您希望某些东西成为默认值时,您都可以定义一个具有该默认值的类(现有类的子类)。然后你使用那个新类。请提出一个新问题,准确显示您希望工作的代码。然后有人可以告诉你该怎么做。
-
没关系,我设法使用带有 ContentTemplate 设置器的样式来做到这一点。不过,谢谢。
标签: c# xml xaml xamarin xamarin.forms