我是 Xamarin.Forms 和 Xaml 的新手。我制作了一个自定义控件,我想在整个应用程序中用作自定义背景。自定义控件作为内容 View 制作,如下所示。
<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 的指定内部堆栈 View 中。
我唯一能想到的就是想出某种方法来访问我的自定义 contentBackground 的 InnerStackView,然后访问该 Stacklayout 的 Children 属性,然后访问该堆栈布局的 Children.add(View) 。尽管这意味着我必须通过代码来完成此操作,并且我希望在 XAML 中实现此行为,因为这对我来说更熟悉。
这是在 XAML 中实现我的目标的唯一方法还是有替代方法?
最佳答案
尝试使用ContentProperty .简单的例子:
[ContentProperty("AddContent")]
public class YourView: ContentView
{
protected ContentView ContentContainer;
public View AddContent
{
get => ContentContainer.Content;
set => ContentContainer.Content = value;
}
......
}
//in xaml
<YourView>
<Label Text="Hello world"/>
</YourView>
关于c# - 自定义布局,Xamarin 表单。最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475301/