方法 : リスト ビュー アイテムの並べ替え

[このドキュメントはプレビュー版であり、後のリリースで変更されることがあります。 空白のトピックは、プレースホルダーとして挿入されています。]

Sort 、の ListViewメソッド サポート、.NET Compact Framework にしませんが上、 IComparerSort メソッドを使用して、 ArrayList インターフェイスを使ってアイテムをまだ並べ替えることができます。

次の表は、定義 3 つのクラスしています。

クラス

説明

ColHeader

このクラスは ColumnHeader クラスから派生した、 ListView コントロールに列を追加して、クリックされた列を並べ替える使用します。 並べ替えの方向を指定する ascending プロパティがあります。true を昇順を指定し、 false の降順を指定します。

SortWrapper

列をクリックしたときはこのクラスのインスタンスが各 ListItem 作成され、 ArrayList に追加。 ラップされた各項目がクリックされた列のインデックスを含むプロパティには含まれます。

このクラスに、SortComparer クラスが含まれています。

SortComparer

SortWrapper クラス内でこのクラスは、 IComparer が並べ替えられてを Compare メソッドは、一度に 2 つのオブジェクトを比較 ArrayList インターフェイスの実装定義します。

ColumnClick イベントのイベント ハンドラーは、とおり並べ替え操作を実行します。

  1. どの列がクリックされた決定するためには、ColHeader クラスのインスタンス作成します。

  2. 反対方向で並べ替えるには、ColHeader オブジェクトの昇順プロパティを設定します。

  3. リスト内の項目数を取得します。

  4. BeginUpdate メソッドで、並べ替え中に、表示を描画を無効にします。

  5. SortWrapper ListView ArrayList 項目ごとを追加されます。

  6. 要素を持つ ArrayList インターフェイスの実装、 SortComparer メソッドで、並べ替えのロジックを含む IComparer クラスの新しいインスタンスを使用して、 Compare で並べ替えます。

  7. アイテムの ListView 制御を消去し、 ArrayList の並べ替えられた項目を持つコントロールを repopulates します。

  8. EndUpdate メソッドで、表示を描画できます。

メモ、SortArrayList メソッドが不安定になったり、並べ替え; を実行します。2 つの要素が等しい場合順序が保持されません。 一方、安定した並べ替えでは、等しい要素の順序が保持されます。

アプリケーションを作成するには

  1. SortWrapper クラスを SortComparer クラスを含むプロジェクトに追加します。

                                ' An instance of the SortWrapper class is created for 
                                ' each item and added to the ArrayList for sorting.
                                Public
                                Class SortWrapper
        Friend sortItem As ListViewItem
        Friend sortColumn AsInteger
        ' A SortWrapper requires the item and the index of the clicked column.PublicSubNew(ByVal Item As ListViewItem, ByVal iColumn AsInteger)
            sortItem = Item
            sortColumn = iColumn
        EndSub
        ' Text property for getting the text of an item.PublicReadOnlyProperty [Text]() AsStringGetReturn sortItem.SubItems(sortColumn).Text
            EndGetEndProperty
        ' Implementation of the IComparer     ' interface for sorting ArrayList items.PublicClass SortComparer
            Implements IComparer
            Private ascending AsBoolean
    
            ' Constructor requires the sort order;        ' true if ascending, otherwise descending.PublicSubNew(ByVal asc AsBoolean)
                Me.ascending = asc
            EndSub
    
            ' Implemnentation of the IComparer:Compare         ' method for comparing two objects.PublicFunction [Compare](ByVal x AsObject, ByVal y AsObject) AsIntegerImplements IComparer.Compare
                Dim xItem As SortWrapper = CType(x, SortWrapper)
                Dim yItem As SortWrapper = CType(y, SortWrapper)
    
                Dim xText AsString = xItem.sortItem.SubItems(xItem.sortColumn).Text
                Dim yText AsString = yItem.sortItem.SubItems(yItem.sortColumn).Text
                Return xText.CompareTo(yText) * IIf(Me.ascending, 1, -1)
            EndFunctionEndClassEndClass
    
                                // An instance of the SortWrapper class is created for
                                // each item and added to the ArrayList for sorting.
                                public
                                class SortWrapper
    {
        internal ListViewItem sortItem;
        internalint sortColumn;
    
    
        // A SortWrapper requires the item and the index of the clicked column.public SortWrapper (ListViewItem Item, int iColumn)
        {
            sortItem = Item;
            sortColumn = iColumn;
        }
    
        // Text property for getting the text of an item.publicstring Text
        {
            get
            {
                return sortItem.SubItems[sortColumn].Text;
            }
        }
    
        // Implementation of the IComparer// interface for sorting ArrayList items.publicclass SortComparer : IComparer
        {
            boolascending;
    
            // Constructor requires the sort order;// true if ascending, otherwise descending.public SortComparer(bool asc)
            {
                this.ascending = asc;
            }
    
            // Implemnentation of the IComparer:Compare// method for comparing two objects.publicint Compare(object x, object y)
            {
                SortWrapper xItem = (SortWrapper) x;
                SortWrapper yItem = (SortWrapper) y;
    
                string xText = xItem.sortItem.SubItems[xItem.sortColumn].Text;
                string yText = yItem.sortItem.SubItems[yItem.sortColumn].Text;
                return xText.CompareTo(yText) * (this.ascending ? 1 : -1);
            }
        }
    }
    
  2. ColHeader クラスをプロジェクトに追加します。

                                ' The ColHeader class is a ColumnHeader object with an 
                                ' added property for determining an ascending or descending sort.
                                ' True specifies an ascending order, false specifies a descending order.
                                Public
                                Class ColHeader
        Inherits ColumnHeader
        Public ascending AsBooleanPublicSubNew(ByVal [text] AsString, ByVal width AsInteger, ByVal align As HorizontalAlignment, ByVal asc AsBoolean)
            Me.Text = [text]
            Me.Width = width
            Me.TextAlign = align
            Me.ascending = asc
        EndSubEndClass
    
                                // The ColHeader class is a ColumnHeader object with an
                                // added property for determining an ascending or descending sort.
                                // True specifies an ascending order, false specifies a descending order.
                                public
                                class ColHeader : ColumnHeader
    {
        publicboolascending;
        public ColHeader(string text, int width,  HorizontalAlignment align, bool asc)
        {
            this.Text = text;
            this.Width = width;
            this.TextAlign = align;
            this.ascending = asc;
        }
    }
    
  3. ColHeader アイテムを追加し、 ListView クラスを持つ列を追加します。

                                ' Set to Details view.
                                Me.listView1.View = View.Details
    
    ' Add columns using the ColHeader class. The fourth    ' parameter specifies true for an ascending sort order.
    listView1.Columns.Add(New ColHeader("Name", 110, HorizontalAlignment.Left, True))
    listView1.Columns.Add(New ColHeader("Region", 50, HorizontalAlignment.Left, True))
    listView1.Columns.Add(New ColHeader("Sales", 70, HorizontalAlignment.Left, True))
    
    ' Add the data.
    listView1.Items.Add(New ListViewItem(NewString() {"Archer, Karen", "4", "0521.28"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Benson, Max", "8", "0828.54"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Bezio, Marin", "3", "0535.22"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Higa, Sidney", "2", "0987.50"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Martin, Linda", "6", "1122.12"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Nash, Mike", "7", "1030.11"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Sanchez, Ken", "1", "0958.78"}))
    listView1.Items.Add(New ListViewItem(NewString() {"Smith, Ben", "5", "0763.25"}))
    
    ' Connect the ListView.ColumnClick event to the ColumnClick event handler.AddHandlerMe.listView1.ColumnClick, AddressOf listView1_ColumnClick
    
                                this.listView1.View = View.Details;
    
    // Add columns using the ColHeader class. The fourth// parameter specifies true for an ascending sort order.
    listView1.Columns.Add(new ColHeader("Name", 110, HorizontalAlignment.Left, true));
    listView1.Columns.Add(new ColHeader("Region", 50, HorizontalAlignment.Left, true));
    listView1.Columns.Add(new ColHeader("Sales", 70, HorizontalAlignment.Left, true));
    
    // Add the data.
    listView1.Items.Add(new ListViewItem(newstring[] {"Archer, Karen","4","0521.28"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Benson, Max","8","0828.54"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Bezio, Marin","3","0535.22"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Higa, Sidney","2","0987.50"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Martin, Linda","6","1122.12"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Nash, Mike","7","1030.11"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Sanchez, Ken","1","0958.78"}));
    listView1.Items.Add(new ListViewItem(newstring[] {"Smith, Ben","5","0763.25"}));
    
    // Connect the ListView.ColumnClick event to the ColumnClick event handler.this.listView1.ColumnClick += new ColumnClickEventHandler(listView1_ColumnClick);
    
  4. コード、並べ替えの実行を追加します。

                                Private
                                Sub listView1_ColumnClick(ByVal sender AsObject, ByVal e As ColumnClickEventArgs)
    
        ' Create an instance of the ColHeader class. Dim clickedCol As ColHeader = CType(Me.listView1.Columns(e.Column), ColHeader)
    
        ' Set the ascending property to sort in the opposite order.
        clickedCol.ascending = Not clickedCol.ascending
    
        ' Get the number of items in the list.Dim numItems AsInteger = Me.listView1.Items.Count
    
        ' Turn off display while data is repoplulated.Me.listView1.BeginUpdate()
    
        ' Populate an ArrayList with a SortWrapper of each list item.Dim SortArray AsNew ArrayList
        Dim i AsIntegerFor i = 0 To numItems - 1
            SortArray.Add(New SortWrapper(Me.listView1.Items(i), e.Column))
        Next i
    
        ' Sort the elements in the ArrayList using a new instance of the SortComparer    ' class. The parameters are the starting index, the length of the range to sort,    ' and the IComparer implementation to use for comparing elements. Note that    ' the IComparer implementation (SortComparer) requires the sort      ' direction for its constructor; true if ascending, othwise false.
        SortArray.Sort(0, SortArray.Count, New SortWrapper.SortComparer(clickedCol.ascending))
    
        ' Clear the list, and repopulate with the sorted items.Me.listView1.Items.Clear()
        Dim z AsIntegerFor z = 0 To numItems - 1
            Me.listView1.Items.Add(CType(SortArray(z), SortWrapper).sortItem)
        Next z
        ' Turn display back on.Me.listView1.EndUpdate()
    EndSub
    
                                private
                                void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
    {
    
        // Create an instance of the ColHeader class.
        ColHeader clickedCol = (ColHeader)this.listView1.Columns[e.Column];
    
        // Set the ascending property to sort in the opposite order.
        clickedCol.ascending = !clickedCol.ascending;
    
        // Get the number of items in the list.int numItems = this.listView1.Items.Count;
    
        // Turn off display while data is repoplulated.this.listView1.BeginUpdate();
    
        // Populate an ArrayList with a SortWrapper of each list item.
        ArrayList SortArray = new ArrayList();
        for (int i = 0; i < numItems; i++)
        {
            SortArray.Add(new SortWrapper(this.listView1.Items[i], e.Column));
        }
    
        // Sort the elements in the ArrayList using a new instance of the SortComparer// class. The parameters are the starting index, the length of the range to sort,// and the IComparer implementation to use for comparing elements. Note that// the IComparer implementation (SortComparer) requires the sort// direction for its constructor; true if ascending, othwise false.
        SortArray.Sort(0, SortArray.Count, new SortWrapper.SortComparer(clickedCol.ascending));
    
        // Clear the list, and repopulate with the sorted items.this.listView1.Items.Clear();
        for  (int i = 0; i < numItems; i++)
            this.listView1.Items.Add(((SortWrapper)SortArray[i]).sortItem);
    
        // Turn display back on.this.listView1.EndUpdate();
    }
    

コードのコンパイル方法

この例では、次の名前空間への参照が必要です。

参照

概念

カスタム コントロールの開発

.NET コンパクトなフレームワーク方法を説明したトピックの検索

その他の技術情報

Windows フォーム コントロール、.NET Framework を最適化します。