无法绑定GridView列中的项列表
我正在构建一个应用程序,向用户显示匹配系列的实时结果。 我按如下方式设置数据结构: Countries->Leagues->Matches
特别是在ViewModel中,我创建了一个可观察的国家集合,如下所示:
private ObservableCollection _countries = new ObservableCollection(); public ObservableCollection Country { get { return _countries; } }
和模型:
public class Country { public string Name { get; set; } public List League { get; set; } } public class League { public string Name { get; set; } public List Event { get; set; } }
类Event包含每个事件的属性,特别是事件的名称,日期等等。
我对这些数据进行了如下评估:
Country country = new Country(); country.Name = "Italy"; League league = new League(); league.Name = "Serie A"; League league2 = new League(); league2.Name = "Serie B"; Event @event = new Event(); @event.MatchHome = "Inter"; Event event2 = new Event(); @event.MatchHome = "Milan"; league.Event = new List(); league2.Event = new List(); league.Event.Add(@event); league2.Event.Add(event2); country.League = new List(); country.League.Add(league); country.League.Add(league2); lsVm.Country.Add(country); //lsVm contains the ViewModel
你如何看待我创建一个名为country
(意大利)的对象,在这种情况下将包含两个联赛(意甲)和(乙级联赛)。 每场联赛实际上都有一场比赛在Serie A -> Inter
和Serie B -> Milan
我将联盟中的两个国家添加到了国家,最后将国家添加到了viewmodel中的可观察集合中。 直到这里没问题。 这个问题出现在xaml中。
所以我在GroupViews中组织了所有这些东西,为此我正在使用CollectionViewSource,特别是:
上面的代码位于我的Window.Resources中,并告诉CollectionViewSource组织国家名称和联盟命名相关联的联赛。 我有两个ListView:
GroupStyle包含将包含每场比赛的联赛,现在问题是我看不到任何联赛和任何比赛’因为这个项目在列表中。 所以为了显示它们我应该在xaml中写下这段代码:
这修复了显示在GroupStyle和GridView中的联盟名称的错误:
但这当然只会显示特定项目..而不是项目列表。 我需要帮助来解决这个问题,我无法弄清楚。 谢谢。
如果要使用ListView
的分组function,则必须为其提供要分组的项目的平面列表(在您的情况下为联盟),而不是标题项。 CollectionView
通过指定GroupDescriptions
为您进行分组。
例如,假设League
类具有Country
属性:
class ViewModel { public ObservableCollection Country { get; } public IEnumerable AllLeagues => Country.SelectMany(c => c.Leagues); } public class League { public string Name { get; set; } public List Event { get; set; } // add Country here public Country Country { get; set; } } class
然后在绑定列时,直接绑定到League
属性,例如:
在组样式中,您可以绑定到Country
属性,就像您所做的那样。
替代解决方案
如果要在WPF中显示任何分层数据,可以使用为其构建的控件(例如Xceed数据网格),也可以将其与内置WPF数据网格的行详细信息一起破解。
这是一个示例XAML(注意它使用您原始的数据结构,没有我上面建议的修改)。 这些基本上是彼此嵌套的3个数据网格。 每个网格都有自己的一组列,因此您可以为每个级别(国家,联盟,事件)定义所需的任何内容。
您还需要我使用的转换器的代码:
public class VisibilityToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value as Visibility? == Visibility.Visible; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => value as bool? == true ? Visibility.Visible : Visibility.Collapsed; }