我有一个简单的 textCell 例如:
<TextCell Text="English" StyleId="disclosure" Tapped="openPage"/>
我希望能够向此单元格添加一个图标,该图标将出现在“英语”一词的左侧。与 iOS 设置中使用的图标的大小和位置完全匹配的图标。
有没有人研究过如何做到这一点?我希望有人能提出一个解决方案,并包括一些关于图标大小等的细节。
最佳答案
您可以创建一个自定义单元格到 自定义 ViewCell 带有图像、文本和 平台 存档。
1) 自定义 ViewCell :
这是自定义 ViewCell 说明的链接:
Customizing a ViewCell
在这个例子中,因为我们在 ViewCell 中有多个元素,所以我们使用 Stacklayout 将 Image 放在 Text 之前,并且我们使用数据绑定(bind)简化了 XAML 中的代码。
下面是演示实现的示例代码:
在 XAML 中:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ImageList"
x:Class="ImageList.ImageListPage">
<ListView x:Name = "listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation = "Horizontal" Margin = "10,10,10,10">
<Image Source = "{Binding Image}" >
<Image.HeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS">30</On>
<On Platform="Android,Windows">20</On>
</OnPlatform>
</Image.HeightRequest>
</Image>
<Label Text = "{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
在代码隐藏中:
using Xamarin.Forms;
using System.Collections.Generic;
namespace ImageList
{
public partial class ImageListPage : ContentPage
{
public ImageListPage()
{
InitializeComponent();
string img1, img2, img3;
switch (Device.RuntimePlatform)
{
case Device.iOS:
img1 = "Gear.jpg";
img2 = "Font.jpg";
img3 = "Sound.jpg";
break;
case Device.Android:
case Device.WinPhone:
default:
img1 = "Gear1.jpg";
img2 = "Font1.jpg";
img3 = "Sound1.jpg";
break;
}
listView.ItemsSource = new List<Item>
{
new Item {Name = "Setting",Image = img1} ,
new Item {Name = "Display",Image = img2} ,
new Item {Name = "Sounds",Image = img3}
};
}
}
}
项目.cs:
using System;
namespace ImageList
{
public class Item
{
public string Name { get; set; }
public string Image { get; set; }
}
}
.
.
2) Device.OnPlatform & Device.RuntimePlatform 属性:
在这个项目中,我们使用 XAML 中的 Device.OnPlatform 属性和 Code-behind 中的 Device.RuntimePlatform 属性来演示如何根据您所在的平台显示不同的图像。这将很有用,因为有时元素可能不会不能在不同的平台上很好地工作。
这是设备类说明的链接:
Device Class
XAML 中的 OnPlate:
我们使用带参数的 OnPlatform 来演示不同平台上的行为。在这种情况下,Android 上的图像高度将小于 iOS 上的图像高度。
代码隐藏中的 Device.RuntimePlatform:
如果应用程序在 Android 上运行,它将使用与 iOS 不同的图像源,例如:“Gear1.jpg”而不是“Gear.jpg”。
以下是不同平台的图片来源:
下面是在 iOS 和 Android 上运行的实际应用程序。
Gear.jpg、Font.jpg、Sound.jpg -> 适用于 iOS 的圆角图像
Gear1.jpg、Font1.jpg、Sound1.jpg -> 用于 Android 的锐角图像
iOS :
安卓:
This是下载演示项目的链接。
关于xamarin - 如何在 Xamarin Forms 中向文本单元格添加图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46463903/