【发布时间】:2020-07-02 09:07:27
【问题描述】:
我正在尝试使用 TableView viewCell 制作表单。一切正常,但我想禁用该 viewCell 上的突出显示功能。我在 Internet 上找不到任何内容,Xamarin 文档中也没有与此相关的内容。
任何帮助将不胜感激。
【问题讨论】:
标签: xamarin xamarin.forms tableview
我正在尝试使用 TableView viewCell 制作表单。一切正常,但我想禁用该 viewCell 上的突出显示功能。我在 Internet 上找不到任何内容,Xamarin 文档中也没有与此相关的内容。
任何帮助将不胜感激。
【问题讨论】:
标签: xamarin xamarin.forms tableview
我相信您正在谈论的突出显示功能是单元格或列表/表格视图用于呈现 Xamarin.Forms TableView/ViewCell 的本机控件的一部分,因此您必须创建 custom renderer,或使用effect 修改本机控件的属性。我个人更习惯于自定义渲染器而不是效果器,所以我将在下面的示例中使用它。
我可以为您提供 iOS 和 Android 的示例,但我必须深入研究 UWP 以获得 UWP 平台的解决方案。
在 Android 上,您可以在用于呈现 Xamarin.Forms TableView 的原生 Android ListView 上将突出显示颜色设置为透明。只需将 C# 代码文件添加到您的 Android 项目并添加以下代码,根据您的解决方案更改命名空间:
using Android.Content;
using TableViewSamples.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(TableView), typeof(CustomTableViewRenderer))]
namespace TableViewSamples.Droid
{
class CustomTableViewRenderer : TableViewRenderer
{
public CustomTableViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
// This sets the highlight color to transparent for all cells in the Android native ListView:
Control.Selector = new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.Transparent);
}
}
}
}
在 iOS 上,高亮颜色是在单元格类上设置的,因此您需要为 ViewCell 而不是 TableView 制作自定义渲染器:
using TableViewSamples.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(ViewCell), typeof(CustomViewCellRenderer))]
namespace TableViewSamples.iOS
{
class CustomViewCellRenderer : ViewCellRenderer
{
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var cell = base.GetCell(item, reusableCell, tv);
// This sets the highlight color to transparent for each UITableViewCell in the iOS native UITableView:
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
return cell;
}
}
}
请注意,这些替换了 Xam.Forms Android 应用中所有 Xam.Forms TableView 实例以及 Xam.Forms iOS 应用中所有 ViewCell 实例的默认渲染器。如果您只需要对某些 TableView 和 ViewCell 执行此操作,则需要将 TableView 和 ViewCell 子类化,并使渲染器在 ExportRenderer 属性中引用这些子类,例如:
[assembly: ExportRenderer(typeof(ViewCellSubClass), typeof(CustomViewCellRenderer))]
和
[assembly: ExportRenderer(typeof(TableViewSubClass), typeof(CustomTableViewRenderer))]
【讨论】: