【发布时间】:2017-03-16 17:10:03
【问题描述】:
我正在开发 Xamarin.Forms 项目中的 Accordion ListView。这意味着您可以单击 ListView 中的 Category Headings,这将展开或折叠其下方的子项。
每个类别标题中有两个图像和一个标题,所以我使用的是 ViewCell。问题在于,当点击类别并显示子项时,类别标题 ViewCell 上的图像会闪烁。
我有两个可观察的集合用于完成 Accordion 功能。一个包含每个父 (MenuItemGroup) 和子 (MenuItem) 项目,一个仅包含应显示的 MenuItem。每次点击标题时,都会触发一个事件,该事件会获取所选类别的索引并切换它的Expanded 属性(显示或隐藏它的子级)。然后调用UpdateListContent()方法刷新ListViewItemSource:
private ObservableCollection<MenuItemGroup> _allGroups;
private ObservableCollection<MenuItemGroup> _expandedGroups;
private void OnHeaderTapped(object sender, EventArgs e)
{
var selectedIndex = _expandedGroups.IndexOf(
((MenuItemGroup)((StackLayout)sender).Parent.BindingContext));
_allGroups[selectedIndex].Expanded = !_allGroups[selectedIndex].Expanded;
UpdateListContent();
}
private void UpdateListContent()
{
_expandedGroups = new ObservableCollection<MenuItemGroup>();
foreach (var group in _allGroups)
{
var newGroup = new MenuItemGroup(group.Title, group.CategoryIcon, group.Expanded);
if (group.Count == 0)
{
newGroup.Expanded = null;
}
if (group.Expanded == true)
{
foreach (var menuItem in group)
{
newGroup.Add(menuItem);
}
}
_expandedGroups.Add(newGroup);
}
_menuItemListView.ItemsSource = _expandedGroups;
}
这是 DateTemplate 和图像绑定:
var menuItemGroupTemplate = new DataTemplate(() =>
{
var groupImage = new Image();
groupImage.SetBinding<MenuItemGroup>(Image.SourceProperty, i => i.CategoryIcon);
var titleLabel = new Label
{
TextColor = Color.White,
VerticalTextAlignment = TextAlignment.Center,
VerticalOptions = LayoutOptions.Center,
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label))
};
titleLabel.SetBinding<MenuItemGroup>(Label.TextProperty, t => t.Title);
var stateIconImage = new Image
{
HorizontalOptions = LayoutOptions.EndAndExpand
};
stateIconImage.SetBinding<MenuItemGroup>(Image.SourceProperty, i => i.IconState);
var menuItemGroupStackLayout = new StackLayout
{
BackgroundColor = Color.FromHex("40474d"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Orientation = StackOrientation.Horizontal,
Padding = new Thickness(10 ,0, 20, 0),
Children = { groupImage, titleLabel, stateIconImage }
};
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += OnHeaderTapped;
tapGestureRecognizer.CommandParameter = menuItemGroupStackLayout.BindingContext;
menuItemGroupStackLayout.GestureRecognizers.Add(tapGestureRecognizer);
var menuItemGroupViewCell = new ViewCell
{
View = menuItemGroupStackLayout,
Height = 63.0
};
return menuItemGroupViewCell;
});
_menuItemListView = new ListView
{
RowHeight = 55,
IsGroupingEnabled = true,
ItemTemplate = menuItemTemplate,
GroupHeaderTemplate = menuItemGroupTemplate,
SeparatorColor = Color.FromHex("40474d"),
HasUnevenRows = true
};
更新 ListView ItemSource 时,groupIcon 和 stateIcon 图像都会闪烁。谁能提供有关如何解决此问题的任何见解?谢谢!
如果您认为有帮助,我可以发布 MenuItemGroup 和 MenuItem 课程。
【问题讨论】:
标签: c# listview xamarin xamarin.forms