ListCollectionView GroupDescription问题

时间:2011-01-24 20:42:44

标签: c# wpf

我有一个名为ContactList的类,它有一个名为AggLabels的属性,它是一个Observable Collection。填充ContactList时,AggLabels集合将包含一些重复的AggregatedLabel。有没有办法使用ListCollectionView按“名称”对这些AggregatedLabels进行分组,以便在将集合绑定到WPF中的listBox时不显示重复项?通过ContactListName在我的代码段组中的代码有一种方法可以修改它以实现我的目标吗?感谢

ContactList

public class ContactList
{           
    public int ContactListID { get; set; }
    public string ContactListName { get; set; }
    public ObservableCollection<AggregatedLabel> AggLabels { get; set; }
}

AggregatedLabel

public class AggregatedLabel
{
    public int ID { get; set; }
    public string Name { get; set; }

}

代码段

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //TODO: Add event handler implementation here.

        ListCollectionView lcv = new ListCollectionView(myContactLists);

        lcv.GroupDescriptions.Add(new PropertyGroupDescription("ContactListName"));

        contactsListBox.ItemsSource = lcv.Groups;

    }

1 个答案:

答案 0 :(得分:0)

由于您尚未提供有关AggLabels使用情况的信息,我希望此解决方案有所帮助:

    <ComboBox Name="contactsListBox" ItemsSource="{Binding MyList}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding ContactListName}"/>
                    <ComboBox ItemsSource="{Binding AggLabels, Converter={StaticResource Conv}}"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

public class AggLabelsDistictConverter : IValueConverter
{
    class AggregatedLabelComparer : IEqualityComparer<AggregatedLabel>
    {

        #region IEqualityComparer<AggregatedLabel> Members

        public bool Equals(AggregatedLabel x, AggregatedLabel y)
        {
            return x.Name == y.Name;
        }

        public int GetHashCode(AggregatedLabel obj)
        {
            return obj.Name.GetHashCode();
        }

        #endregion
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is IEnumerable<AggregatedLabel>)
        {
            var list = (IEnumerable<AggregatedLabel>)value;
            return list.Distinct(new AggregatedLabelComparer());
        }}}

正如您所看到的,我以通常的方式绑定ContactListEnumerable,并且每个ContactList容器中的AggLabels列表 - 通过转换器删除重复项。