首页 > 解决方案 > xaml ControlTemplate 中的 TemplateBinding 不起作用

问题描述

在 App.xaml 中放置的 ControlTemplate 中,我尝试从使用的 ViewModel 获取布尔属性,以使元素(在本例中为 activityIndi​​cator)在 Content xaml 中可见。

财产:

Private bool isLoading;
public bool IsLoading
{
   get => this.isLoading;
   set => this.SetProperty(ref this.isLoading, value);
}

内容页:

ControlTemplate="{StaticResource Template__Page_Scrollable}"

ControlTemplate(我会将 ActivityIndi​​cator 集成到 StackLayout 中,但首先我只想通过将背景颜色设置为 Aqua 来显示 StackLayout 本身):

    <ControlTemplate x:Key="Template__Page_Scrollable">
        <AbsoluteLayout x:Name="ActivityIndicator">
            <ScrollView Style="{StaticResource Page_Scrollable__ScrollContainer}" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All">
                <ContentPresenter AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All"/>
            </ScrollView>
            <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" 
                         IsEnabled="{TemplateBinding Parent.BindingContext.IsLoading}" 
                         IsVisible="{TemplateBinding Parent.BindingContext.IsLoading}" BackgroundColor="Aqua">
            </StackLayout>
        </AbsoluteLayout>
    </ControlTemplate>

由于我的研究,这应该可以通过我收到消息“无法解析符号'父'”而没有'父'我总是得到真实的结果。

我试过例如:

标签: xamlxamarincontroltemplateabsolutelayouttemplatebinding

解决方案


如果你真的有你的ControlTemplate设置ContentPage,例如:

<ContentPage 
...
ControlTemplate="{StaticResource Template__Page_Scrollable}">

这是不正确的。Parentin 是ControlTemplate指托管控件模板的视图的父视图。ContentPage 没有父视图。

相反,您需要在 ContentPage 的 ContentView 上设置控件模板,例如:

<ContentPage ...>
    <ContentView ControlTemplate="{StaticResource Template__Page_Scrollable}" >
       ...
    </ContentView>
</ContentPage>

推荐阅读