开发者

How to add a special item to a listview and keep it at the top?

I have a SortableListView of which I set the ItemsSource via a binding. Something like the following:

  <SortableListView ItemsSource="{Binding Items}">
    <SortableListView.View>
      <GridView>
        <SortableGridViewColumn
          Header="Name"
          SortProperty="ProductName"
          DisplayMemberBinding="{Binding ProductName}"/>
      </GridView>
    </SortableListView.View>
  </SortableListView>

When the window gets shown I initialize and fill the ObservableCollection<Item> Items.

Now I would like to add one (and only one) special item to the top of开发者_运维问答 the list and always keep this as the first item, regardless of the sort order.

Currently I can think of two possible ways to achieve this:

  1. Create a very special data template for my ListView where I can add the special item and theme the ListView to process everything accordingly.
  2. Bind to the header and handle the click event to perform the sorting in my code-behind file and insert the special item at the top.

Option 1 seems like too much and too complicated work and option 2 is something I would like to avoid.

Are there any alternative solutions to this I am missing? If not, what would be the best option to achieve this, and how should I approach the theme option?


I'm taking a guess here but I'm assuming you're using this control?:

http://thejoyofcode.com/Sortable_ListView_in_WPF.aspx

If so, it uses the ICollectionView to manage it's sorting. ICollectionView is very flexible and allows for multiple fields to be sorted (you know like in SQL: SORT BY Field1 ASC, Field2 DESC).

I think what you want to do is insert an extra sort description before adding the description for the property the user has chosen. That way it will sort by your 'flagged' items first, then the chosen property name.

(code adapted from above article)

private void Sort(string sortBy, ListSortDirection direction)
{
    ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource);

    if (dataView != null)
    {
        dataView.SortDescriptions.Clear();

        dataView.SortDescriptions.Add(new SortDescription("IsAtTop", ListSortDirection.Ascending));
        SortDescription sd = new SortDescription(sortBy, direction);
        dataView.SortDescriptions.Add(sd);
        dataView.Refresh();
    }
}

So you'd just need to add a bool property to your object called 'IsAtTop'.

Hopefully this is what you need....


In your view model you can keep a separate ObservableCollection<T> that returns your list with one "special" item added at the top. If you hook the CollectionChanged event of the original ObservableCollection<T> so that you can call a PropertyChanged notification on your collection you can achieve the desired behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜