c# - 自定义布局,Xamarin 表单。最佳方法

标签 c# xaml xamarin.forms app.xaml

我是 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/

相关文章:

xamarin.forms - 在 Xamarin.Forms 中使用 PCLStorage 读取文本文件

c# - 类型 'UserControl' 不支持直接内容

c# - 有没有我可以在属性上使用的属性来告诉 DataGridView 如何设置列的格式?

c# - 继承问题

c# - 为什么 OnPropertyChanged 在代码隐藏中不起作用?

c# - XAML 中的 Xamarin.Forms ListView 自动高度

xaml - Xamarin.forms 按钮对齐

c# - .Net SqlConnection、服务器身份验证和证书固定

c# - UWP应用程序不断抛出未经授权的访问异常

c# - 在通过敲击键盘上的 Enter 触发点击事件之前,我可以使用哪个事件来触发对标签的更新?