2017-07-12 98 views
0

我需要更改Xamarin.Forms应用程序中的列表视图的选定项目颜色。 所以我创建了一个自定义渲染...Xamarin.Forms iOS listview选定的项目颜色

PCL C#:

public class DarkViewCell : ViewCell {} 

PCL XAML:

<ListView> 
    <ListView.ItemTemplate> 
    <DataTemplate> 
     <local:DarkViewCell> 
     <ViewCell.View> 
      ... Stuff ... 
     </ViewCell.View> 
     </local:DarkViewCell>    
    </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 

的iOS

public class DarkViewCellRenderer : ViewCellRenderer 
{ 
    private UIView bgView; 

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv) 
    { 
     var cell = base.GetCell(item, reusableCell, tv); 

     cell.BackgroundColor = UIColor.Black; 
     cell.TextLabel.TextColor = UIColor.White; 

     if (bgView == null) 
     { 
      bgView = new UIView(cell.SelectedBackgroundView.Bounds); 
      bgView.Layer.BackgroundColor = UIColor.FromRGB(48,48,48).CGColor; 
      bgView.Layer.BorderColor = UIColor.FromRGB(48, 48, 48).CGColor; 
      bgView.Layer.BorderWidth = 2.0f; 
     } 

     cell.SelectedBackgroundView = bgView; 

     return cell; 
    } 
} 

但不工作。我也试图改变SelectionStyle但没有...

编辑

在一个新项目,它的工作原理。和代码是一样的

回答

1

我不是100%肯定,但我删除

<x:Arguments> 
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy> 
</x:Arguments> 

,并开始工作。

0

尝试设置:

public override UITableViewCell GetCell(Cell item, UITableView tv) 
{ 
    var cell = base.GetCell(item, tv); 
    cell.SelectedBackgroundView = new UIView() { BackgroundColor = UIColor.Black }; 
    return cell; 
} 

更新: 我只是用你的代码在一个虚拟的项目和它的作品,因为它应该。您是否添加了程序集属性来注册自定义渲染器?

[assembly: ExportRenderer(typeof(DarkViewCell), typeof(DarkViewCellRenderer))] 
namespace MyProject.iOS 
{ 
    public class DarkViewCellRenderer : ViewCellRenderer 
    { 
    } 
} 
+0

这是我尝试的第一件事 –

+0

自定义渲染器中的其他任何东西是工作还是根本不工作?我只是从我自己的一个项目中复制了一段代码,它完全按照需要工作。 –

+0

更新了我的答案。 –

0

我最近也有类似的问题,我发现设置单元格的背景色是使用细胞ContentView

尝试使用在你的GetCell方法如下最好的办法

cell.ContentView.BackgroundColor = UIColor.Black; 
0

按照下面的代码它的工作对我来说

public override UITableViewCell GetCell(Cell item, UITableView tv) 
    { 
    var cell = base.GetCell(item, tv); 

    cell.SelectedBackgroundView = new UIView { 
    BackgroundColor = UIColor.DarkGray, 
    }; 
    return cell; 
} 

下面的链接是对你有用

Xamarin.Forms ListView: Set the highlight color of a tapped item

相关问题