ControlTemplate包含多个内容演示者。如何将ContentPresenter的内容绑定到Xamarin Forms中的DataTemplate的值

时间:2017-07-28 11:52:00

标签: c# xaml xamarin mvvm xamarin.forms

我有一个自定义控件Xamarin Forms,看起来像这样:

public class CardView : Frame
{
    public static readonly BindableProperty HeaderDataTemplateProperty = BindableProperty.Create("HeaderDataTemplate", typeof(DataTemplate), typeof(HeaderCardView), null, BindingMode.TwoWay);
    public static readonly BindableProperty BodyDataTemplateProperty = BindableProperty.Create("BodyDataTemplate", typeof(DataTemplate), typeof(HeaderCardView));

    public DataTemplate HeaderDataTemplate
    {
        get => (DataTemplate)GetValue(HeaderDataTemplateProperty);
        set => SetValue(HeaderDataTemplateProperty, value);
    }

    public DataTemplate BodyDataTemplate
    {
        get => (DataTemplate)GetValue(BodyDataTemplateProperty);
        set => SetValue(BodyDataTemplateProperty, value);
    }

    public CardView()
    {
        if (Device.RuntimePlatform.Equals("iOS"))
        {
            HasShadow = false;
            OutlineColor = Color.Transparent;
            BackgroundColor = Color.Transparent;
        }
    }
}

我们的想法是创建一个“卡片”控件,可以为标题和正文定义2个DataTemplates。

所以我定义了一个使用2个内容演示者的ControlTemplate:

<ControlTemplate x:Key="HeaderCardControlTemplate">
    <StackLayout>
        <ContentView Padding="5" BackgroundColor="#a6192e">
            <ContentPresenter Content="{TemplateBinding Parent.HeaderDataTemplate, Mode=TwoWay}"></ContentPresenter>
        </ContentView>
        <ContentView>
            <ContentPresenter Content="{TemplateBinding Parent.BodyDataTemplate}"></ContentPresenter>
        </ContentView>
     </StackLayout>
</ControlTemplate>

并像这样使用它:

<controls:HeaderCardView ControlTemplate="{StaticResource HeaderCardControlTemplate}">                                        
    <controls:HeaderCardView.HeaderDataTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Label FontAttributes="Bold" Text="{Binding Value}" Grid.Row="0" Grid.Column="0"></Label>
                <Label FontAttributes="Bold, Italic" Text="{Binding Type}" HorizontalOptions="End" Grid.Row="0" Grid.Column="1"></Label>
            </Grid>
        </DataTemplate>                                    
    </controls:HeaderCardView.HeaderDataTemplate>
</controls:HeaderCardView>

然而,ContentPresenter没有显示假设为Grid的HeaderDataTemplate。

关于我遗失或做错的任何想法?

0 个答案:

没有答案