c# - 有没有办法从 StaticResource 设置 StackLayout 或 Grid 的内容

标签 c# .net xaml xamarin xamarin.forms

查看我的 XAML,我注意到这些区域基本上是彼此重复的,因为我喜欢保持干净,所以我在想是否有一种方法可以减少 XAML 中的重复代码。

所以我想要做的是能够为 StackLayout、Grid、Frame 等控件设置内容。

我已经创建了页面级资源,但我不确定如何使用它。

<ContentPage.Resources>
    <StackLayout x:Key="CommonDetails">
        <Label Text="First Name"/>
        <Label Text="Last Name"/>
    </StackLayout>
</ContentPage.Resources>

<StackLayout>
    <CommonDetails>
    <Label Text="Extra Uncommon Data"/>
</StackLayout>

<StackLayout>
    <CommonDetails>
    <Label Text="Extra Uncommon Data"/>
    <Label Text="Extra Uncommon Data"/>
    <Label Text="Extra Uncommon Data"/>
</StackLayout>

最佳答案

Resources中,您可以定义一个ControlTemplete:

<ContentPage.Resources>
    <ControlTemplate x:Key="commonDetails">
        <StackLayout>
            <Label Text="First Name"/>
            <Label Text="Last Name"/>
            <ContentPresenter/>
        </StackLayout>
    </ControlTemplate>
</ContentPage.Resources>

这里是棘手的部分,因为为了使用它,您将需要一个 ContentView,但在您的情况下,“正常”ContentView 不会这样做因为它们只接受一个 child,所以这是一项工作:您必须创建一个特殊的 ContentView 来接受多个 View 。

您可以按如下方式执行此操作:

// Overriding the ContentProperty allows you 
// to have a ContentView that accepts multiple childs.
[Xamarin.Forms.ContentProperty("Contents")]
public class View1 : ContentView
{
    StackLayout contentStack { get; } = new StackLayout();
    
    public IList<View> Contents { get => contentStack.Children; }

    public View1()
    {
        Content = contentStack;
    }
}

有了这些,剩下的就非常简单了,因为在任何 Page 中,您都可以定义自定义 ControlTemplate 并将其设置为您特殊的 ContentView,如下

<local:View1 ControlTemplate="{StaticResource commonDetails}">
    <Label Text="Occupation1"/>
    <Label Text="Occupation2"/>
</local:View1>

就是这样,我觉得这很有用!

关于c# - 有没有办法从 StaticResource 设置 StackLayout 或 Grid 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65412725/

相关文章:

.net - VB 中有 "coroutine"功能吗?

c# - 给定键不存在于字典 Xamarin 表单中

c# - .net 核心中的 CPU 使用率(至少在 Windows 上)

c# - 是否对通用原因装箱执行空检查?

c# - 如何在 .NET 中使用 Hot Chocolate 扩展 GraphQL 自省(introspection)类型

c# - ASP.NET 文件浏览器路径转换

xaml - 如何将特定值传递给转换器参数?

wpf - 覆盖 generic.xaml 中定义的样式

c# - 有没有更好的方法从 C# 中的整数中删除字符?

c# - Windows Azure 入门