Xamarin表单 - 我的ContentPresenter不会显示其内容

时间:2017-08-15 15:09:04

标签: xaml xamarin xamarin.forms

我还习惯了Xamarin Forms,所以我有以下名为PopupFrame的控件:

PopupFrame.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PopupFrame : ContentView
{
    public static readonly BindableProperty PopupContentProperty =
        BindableProperty.Create(nameof(PopupContent), typeof(View), typeof(PopupFrame));

    public View PopupContent
    {
        get { return (View)GetValue(PopupContentProperty); }
        set { SetValue(PopupContentProperty, value); }
    }

    public PopupFrame()
    {
        InitializeComponent();
    }
}

PopupFrame.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestApp.Core.Controls.PopupFrame">
    <Frame>
        <StackLayout>
            <Label Text="--- TEST TITLE ---" />

            <ContentPresenter Content="{TemplateBinding PopupContent}" />
        </StackLayout>
    </Frame>
</ContentView>

在我看来:

<popCtl:PopupFrame HorizontalOptions="Center"
                   VerticalOptions="Center">
    <popCtl:PopupFrame.PopupContent>
        <ListView x:Name="ListUsers">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <Label Text="{Binding Name}"
                                   HorizontalOptions="CenterAndExpand"
                                   VerticalOptions="Center" />
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        </popCtl:PopupFrame.PopupContent>
</popCtl:PopupFrame>

所以发生的事情是,当ContentView控件显示时,只显示标签(显示文本 - TEST TITLE - 但不显示ListView )。

我也尝试用ContentView替换ContentPreseter,但结果相同:我的ListView没有显示。我确保数据确实存在于ListView的ItemsSource中(在代码隐藏中设置)。

我的ContentView设置错了吗?

1 个答案:

答案 0 :(得分:2)

TemplateBinding只能用于从控件模板内部进行绑定。为了使您的绑定有效 - 您可以使用ReferenceExtension来引用父控件。

例如,更新您的绑定,如下所示:

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestApp.Core.Controls.PopupFrame"
             x:Name="_parent">
    <Frame>
        <StackLayout>
            <Label Text="--- TEST TITLE ---" />

            <ContentPresenter 
                 Content="{Binding Path=PopupContent, Source={x:Reference _parent}}" />
        </StackLayout>
    </Frame>
</ContentView>