[WPF] sorting by clicking a column header in listview

Source: Internet
Author: User

This is a very common function, and the requirements are very simple. Column header A small triangle is displayed to indicate the current location. Header On the forward or reverse order. Microsoft Msdn Already Provides implementation methods . In Microsoft's method Columnheader Template To achieve this, we need to maintain at least two Header Template , A positive triangle and an inverted triangle. Click Header Switch Template . If your Listview Only Sort Function. But if your Listview Still in Header Provided in Filter Function? If you need to enable or disable Sort And Filter Function? Then you need 6 Items Template To process Sort And Filter . If Header There are several types of Text Header , Image Header ) Or want to add more features? Obviously, Microsoft can only use this method for technical demonstration (of course MsdnThis is the purpose. Google Search WPF listview sort , You can find many different implementation methods.

1.Switchonthecode: UseAdorner Layer, RewriteAdornerOfOnrenderMethod,DrawA triangle. You can draw a triangle, and draw a triangle with luminous, gradient, and animation effects,CodeIt will become difficult to maintain. And cannot be usedBlendEdit the style. However, the idea is very good, because it does not occupy any existing properties of the control, there will be no problem of functional combinations in Microsoft's approach.

2. jeol rumerman's blog : Inherit gridviewcolumn and extend sort function. Use header template . Worse, using inheritance to add a function is not a good design. Similarly, you must add the filter function, is it necessary to inherit a filteredgridviewcolumn and filteredandsortedgridviewcolumn what? Not only do you need to process the combination of template , but also generate class expansion, which is really not desirable.

3.Codeproject wpflistviewsorter: Same as Microsoft's approach, it only uses customSorterThe function solves the problem of MicrosoftColumn headerAsSort Property.

4.Thejoyofcode: PassAttached PropertySolved the same problem, and there is no interface display implementation. It also inheritsSortablelistview. The disadvantages will not be explained.

5.Marlongrech: ProvidesDisable/enable sortFunction. But it is also usedHeadertemplateImplement the interface. (Suddenly discoveredWordPressAccessible)

I have not found an implementation method that meets my requirements. Every solution focuses only on the point where I want to solve the problem. Of course inBlogTo make the example simple. Then let me integrate the problems they solve into an example. There are not many requirements.

1.Existing functions are not affected.

2.The existing attribute is not exclusive.

3.Use combination instead of inheritance.

Solution 1: UseAdorner LayerIs a good idea,Adorner LayerIt is equivalent to a canvas, where I draw other functions, so it does not affect the existing functions or exclusive existing attributes. In this exampleTagTo describe which attribute is used for sorting. We useAttached PropertyReplace it. Then there is one problem left-do not draw a triangle. We want to useTemplate. In this way, different parts of the interface can have different effects without modifying the code. But the problem isAdornerYes NoTemplate.

For more information, seeAdorner LayerOfArticle.

1.Adorners in WPF

2.Visual level programming vs logical level programming

After writing the code for one night, I finally came up with a good self-feeling implementation. InListviewAddSortFunction, you only need to addAttached PropertyYou can. The Code is as follows.

 

Add sort to listview

< Listview Ext: listviewbehavior. headersort = "True"
Itemssource =" {Binding} " >
< Listview. View >
< Gridview >
< Gridviewcolumn Header = "Name"
Displaymemberbinding =" {Binding itemname} "
Ext: listviewbehavior. sortfield = "Itemname" />
< Gridviewcolumn Header = "Value"
Displaymemberbinding =" {Binding itemvalue} "
Ext: listviewbehavior. sortfield = "Itemvalue" />
</ Gridview >
</ Listview. View >
</ Listview >

 

 

InGridviewcolumnAlso usedAttached PropertySpecify the columns to sort. If this parameter is not specifiedHeaderAs the sorting attribute.

UsedShevaIn the exampleUielementadorner(Slightly changed) put a custom controlListsortdecoratorIn the current sorting column. The Code is as follows.

 

Uielementadorner

Using System. collections;
Using System. windows;
Using System. Windows. documents;
Using System. Windows. Media;

NamespaceSortlistview. extention
{
Public ClassUielementadorner: adorner
{
PrivateUielement child;

///   <Summary>
///  
///   </Summary>
///   <Param name = "element"> </param>
///   <Param name = "direction"> </param>
Public Uielementadorner (uielement element, uielement child)
: Base (Element)
{
This . Child = Child;
Addlogicalchild (child );
Addvisualchild (child );
}

Protected OverrideSize arrangeoverride (size finalsize)
{
Child. Arrange (NewRect (finalsize ));

ReturnFinalsize;
}

Protected OverrideSize measureoverride (size constraint)
{
Child. Measure (constraint );

ReturnAdornedelement. rendersize;
}

protected override int visualchildrencount
{< br> Get { return 1 ;}
}

Protected OverrideVisual getvisualchild (IntIndex)
{
ReturnChild;
}

Protected   Override Ienumerator logicalchildren
{
Get
{
Arraylist list =   New Arraylist ();
List. Add (child );
Return (Ienumerator) List. getenumerator ();
}
}

///   <Summary>
///  
///   </Summary>
Public Uielement child
{
Get { Return Child ;}
}
}
}

 

The appearance of a triangle can be determined by listsortdecorator.. The default format is as follows.

 

Listsortdecorator

< Controltemplate Targettype =" {X: Type Ext: listsortdecorator} " >
< Path X: Name = "Path" Data = "M0, 0l2, 0 1, 1z"
Fill =" {Templatebinding foreground} "
Stroke =" {Templatebinding foreground} "
Horizontalalignment =" {Templatebinding horizontalcontentalignment} "
Verticalalignment =" {Templatebinding verticalcontentalignment} "
Width = "7" Height = "4" Stretch = "Fill" />
< Controltemplate. triggers >
< Trigger Property = "Sortdirection" Value = "Descending" >
< Setter Targetname = "Path" Property = "Data" Value = "M0, 1l2, 1l1, 0z" />
</ Trigger >
</ Controltemplate. triggers >
</ Controltemplate >

 

 

In this way, you can convenientlyBlendDraw a triangle and make an animation. Display Effect.

 

Figure1.Interface Effect

 

The entire sample code can be downloaded from here. You are welcome to correct the error.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.