查看FlowViewCell的源码,你会发现FlowViewCell的超类不是ViewCell,而是ContentView .所以如果你关注这个博客是不行的。
namespace DLToolkit.Forms.Controls
{
//
// Summary:
// FlowListView content view cell.
[Preserve(AllMembers = true)]
public class FlowViewCell : ContentView, IFlowViewCell
{
//
// Summary:
// Initializes a new instance of the DLToolkit.Forms.Controls.FlowViewCell class.
public FlowViewCell();
//
// Summary:
// Raised when cell is tapped.
public virtual void OnTapped();
}
}
在 FlowListView.FlowColumnTemplate 中的控件背景上创建绑定,在 FlowItemTappedCommand 中进行更改。
后面的代码
public class Model : INotifyPropertyChanged
{
public string Title
{
get;set;
}
private Color bgColor;
public Color BGColor
{
set {
if(value != null)
{
bgColor = value;
NotifyPropertyChanged();
}
}
get
{
return bgColor;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ViewModel
{
public ObservableCollection<Model> List { set; get; }
public ICommand ItemTappedCommand { get; set; }
public ViewModel()
{
List = new ObservableCollection<Model>();
List.Add(new Model() { Title = "1" ,BGColor = Color.White });
List.Add(new Model() { Title = "2" , BGColor = Color.White });
List.Add(new Model() { Title = "3", BGColor = Color.White });
List.Add(new Model() { Title = "4", BGColor = Color.White });
ItemTappedCommand = new Command((obj)=> {
//reset the bg color
foreach(var model in List)
{
model.BGColor = Color.White;
}
Model mo = obj as Model;
int index = List.IndexOf(mo);
mo.BGColor = Color.Red;
});
}
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
ViewModel vm = new ViewModel();
BindingContext = vm;
}
}
在xml中
<flv:FlowListView FlowColumnCount="3"
SeparatorVisibility="None" HasUnevenRows="false"
FlowItemTappedCommand="{Binding ItemTappedCommand}"
FlowItemsSource="{Binding List}" >
<flv:FlowListView.FlowColumnTemplate>
<DataTemplate>
<Label HorizontalOptions="Fill"
BackgroundColor="{Binding BGColor}"
VerticalOptions="Fill"
XAlign="Center"
YAlign="Center"
Text="{Binding Title}"/>
</DataTemplate>
</flv:FlowListView.FlowColumnTemplate>
</flv:FlowListView>
此外,CollectionView 在 XF 4.3 之后可用。您可以使用它来代替第三方库。检查https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/introduction。