xaml - 重用大量 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 中重用它们。
我该如何做到这一点,以便我可以在两个页面上重用前两个网格行的代码,并且能够拥有第三个网格布局的不同内容?如果需要,我可以使用上面的代码隐藏设置两个标签。
我对应用程序开发很陌生,因此对以下代码的任何额外解释源都适用。
解决方案
推荐阅读
- django - 带有 azuread-oauth2 的 exchange_access_token 上的 openEdx 服务器错误
- c# - 将 int 转换为字符串 JsonConvert
- ios - 为 iOS 构建时没有开发团队错误
- vba - Word中的VBA循环查找通配符字符串第一次出现
- node.js - 任务计划管理
- python - 为熊猫数据框中的重复值添加唯一标识符
- string - 部分字符串在 Bash 中拆分
- vba - 如何清除 Outlook 正文中的所有格式
- css - 我的问题是关于 CSS 通用选择器
- node.js - 尝试在 http.put 正文中发送 2+ 个对象,后端返回空正文