【问题标题】:Nest Content inside ContentView [duplicate]在 ContentView 中嵌套内容 [重复]
【发布时间】: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>

从中,您可以看到我希望&lt;Entry Placeholder="PlaceholderText"/&gt; 覆盖&lt;View x:Name="FieldContent"/&gt; 对象,但我无法使其工作。它总是会覆盖整个 ContentView,只显示占位符 Entry

我所做的唯一改进是在 ContentView 的 C# 类中添加了[ContentProperty(nameof(Field))],这使得它的原始内容可以显示,但Entry 对象将不再出现。

那么我怎样才能让Entry 对象正确覆盖ContentView 中的View 对象呢?提前致谢。

PS:我尝试将&lt;View x:Name="FieldContent"/&gt; 替换为&lt;ContentPresenter x:Name="FieldContent"/&gt; 并改用ContentPresenter.Content,但无济于事。

【问题讨论】:

  • 首先,去掉[ContentProperty...]属性——在一个ContentView中,整个内容就是ContentProperty;您绝对不希望 Field 成为那样;这将覆盖您的整个 StackLayout。在链接的答案中,请注意 &lt;ContentView x:Name="contentView" ... ControlTemplate="{StaticResource TealTemplate}"&gt;That 声明使用 ControlTemplate。然后定义该模板,如链接答案所示。
  • @ToolmakerSteve 这正是我所需要的,谢谢!但是,是否可以让 ContentView 对象从代码而不是 XAML 中获得所需的 ContentTemplate?我看到ControlTemplate={StaticResource TargetControlTemplate} 行在该类型的每个实例中重复,所以我想知道是否可以将对象的ControlTemplate 属性默认为一个值。
  • 我不确定我是否理解这个问题。每当您希望某些东西成为默认值时,您都可以定义一个具有该默认值的类(现有类的子类)。然后你使用那​​个新类。请提出一个新问题,准确显示您希望工作的代码。然后有人可以告诉你该怎么做。
  • 没关系,我设法使用带有 ContentTemplate 设置器的样式来做到这一点。不过,谢谢。

标签: c# xml xaml xamarin xamarin.forms


【解决方案1】:

您可以在 code behind(viewmodel) 中创建ControlTemplate,并将其绑定到 xaml 中。

后面的代码

ControlTemplate MyTemplate = new ControlTemplate(()=> {
      return new Entry { Placeholder= "PlaceholderText" };
});

页面 Xaml

<local:LoggingField ControlTemplate="{Binding MyTemplate}"/>

但是,这完全不推荐,最好的方法是将ControlTemplate放在xaml中。

【讨论】:

  • 谢谢!但是,我发现自己每次在页面中引用 LoggingField 对象时都会重复相同的 ControlTemplate={StaticResource MyControlTemplate} 行。有没有办法将LoggingField对象默认分配给某个ControlTemplate
猜你喜欢
  • 2020-05-02
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
相关资源
最近更新 更多