我是Xamarin.Forms和Xaml的新手 . 我已经制作了一个自定义控件,我希望在整个应用程序中将其用作自定义背景 . 自定义控件是作为内容视图制作的,看起来像这样 .
<ContentView.Content>
<ScrollView>
<StackLayout>
<RelativeLayout Padding="0" BackgroundColor="Teal" VerticalOptions="Start">
<Image Source="TopBG" BackgroundColor="Purple" Aspect="Fill" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.6}" />
</RelativeLayout>
<Frame Padding="0" Margin="0,-25,0,0" CornerRadius="25" BackgroundColor="{StaticResource Key=Charcoal}">
<StackLayout Margin="0,0,0,0" VerticalOptions="StartAndExpand" BackgroundColor="Transparent" x:Name="InnerStack">
<!--I can insert custom controls here, but htat would determine this custom contentView for one purpose only-->
</StackLayout>
</Frame>
</StackLayout>
</ScrollView>
</ContentView.Content>
然后在我的ContentPage上实现自定义控件:
<ContentPage.Content>
<CustomLayouts:ContentBackground>
<!-- I would instead like to be able to add content here, and have it go into the stacklayout of the custom view.
This way i could utilize the same background but have different content go into it depending on my wishes -->
</CustomLayouts:ContentBackground>
</ContentPage.Content>
如果我在后面的示例中添加了一个标签,它只是覆盖所有内容并放置一个标签,但不是在我的ContentBackground的指定内部堆栈视图中 .
我唯一能想到的是找到一些方法来访问我的自定义contentBackground的InnerStackView,然后访问该Stacklayout的children属性,然后访问Children.add(View)到该堆栈布局 . 虽然这意味着我将不得不从代码中做到这一点,我想在XAML中实现这种行为,因为这对我来说更为熟悉 .
这是唯一的方法还是有替代方法来实现我在XAML中的目标?
2 回答
尝试使用ContentProperty . 简单示例:
如果有人仍在尝试此操作,您可以使用
ControlTemplate
在多个页面或应用程序范围内查看,这里的魔力是
ContentPresenter
,你可以在里面放任何东西都会显得很好 . 然后使用所需的模板,将其设置为ContentView.ControlTemplate
,如此,查看官方文档here .
如果要创建可以在任何页面上插入的自定义控件/布局,那么您可以使用
ContentPresenter
创建自己的ContentView
来保存您的视图子项,其中
SomeContent
可以是BindableProperty
类型的BindableProperty
.您还可以看到自定义布局here的示例 .