首页 > 解决方案 > 重用大量 Xaml 界面元素

问题描述

我之前就这个问题发表了一个非常相似的帖子,其中我询问了如何重用某些 Xaml 代码的一部分。虽然这适用于我拥有的小元素,但在目前的规模上并不完全有效。

使用 Xamarin,我有一个带有两页的选项卡式布局。一个页面由一个具有三层的网格组成,其中两个在两个页面上都是相同的。第三层需要在两个页面上有所不同。两个页面当前都在同一个文件中。这意味着大部分代码只是简单的复制粘贴,这使得编辑前两行中某些标签的值变得更加困难,因为它们不能具有相似的 ID/名称。

我目前使用 setter 在代码隐藏中设置了一个字符串变量。

string _vesselCode;
public string VesselCode
{
    get
    {
        return _vesselCode;
    }
    set
    {
        _vesselCode = value;
        currentVessel.Text = _vesselCode;
        currentVesselClone.Text = currentVessel.Text;
    }
}

虽然这可行,但我仍然有很多被欺骗的代码(如下所示)。

这是每一页的内容。唯一特定于页面的内容位于底部。其余的按字面意思复制粘贴到第二页。下面的代码没有任何 ID。

<Grid RowSpacing="0">
        <Grid.RowDefinitions>
            <!-- first row from top {0} - app name, vessel. -->
            <RowDefinition Height="Auto"/>

            <!-- second row {1} - originele freq // nieuwe frequentie. -->
            <RowDefinition Height="Auto"/>

            <!-- third row {2} - tablayout. -->
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- header contents -->
        <Grid Grid.Row="0" StyleClass="headerBar">

            <StackLayout Grid.Column="0" HorizontalOptions="Start" StyleClass="inGrid">


                <Label StyleClass="header"
                Text="OV Frequentie"/>
                <Label StyleClass="headerSub"
                Text="huidig voertuig:"/>

            </StackLayout>

        </Grid>

        <!-- freq bar contents -->
        <Grid Grid.Row="1" StyleClass="subHeaderBar">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <BoxView Grid.ColumnSpan="2"
                 BackgroundColor="#2d313a"
                 WidthRequest="2"
                 HeightRequest="2"
                 Margin="5,0,5,-3"/>

            <StackLayout Grid.Column="0" HorizontalOptions="Start" StyleClass="inGrid">
                <Label StyleClass="generalSmallText"
                Text="originele freq: 10"/>
            </StackLayout>

            <StackLayout Grid.Column="1" HorizontalOptions="End" StyleClass="inGrid">
                <Label StyleClass="generalSmallText"
                Text="nieuwe freq: 10"/>
            </StackLayout>
        </Grid>
        <!-- info page content -->
        <Grid Grid.Row="2">
            <StackLayout StyleClass="infoDisplayPage">

                <!-- page unique stuff -->

            </StackLayout>
        </Grid>
    </Grid>

就像我说的那样,这种方法有效,但代码非常糟糕。我希望能够更改多个标签的值,但我不能给它们相同的 ID。这意味着我必须始终将这些值设置两次,或者在其中一个标签上获取一些设置属性,自动设置另一个/在代码中使用此类设置器具有属性。

我被告知要使用更大区域的代码,我可以使用 ContentView。但是,我似乎无法在两个 ContentPages 中重用它们。

我该如何做到这一点,以便我可以在两个页面上重用前两个网格行的代码,并且能够拥有第三个网格布局的不同内容?如果需要,我可以使用上面的代码隐藏设置两个标签。

我对应用程序开发很陌生,因此对以下代码的任何额外解释源都适用。

标签: xamlxamarincode-reuse

解决方案


推荐阅读