0

WinForms で、複数選択が有効になっているリストボックスがあり、リストボックスに 50 個の項目が含まれており、リストボックスの最初の項目のみが選択されているとします...

...次に、(SetSelectedメソッドを使用して) 最後の項目を選択すると、リストボックスが (垂直スクロールと共に) 一番下にジャンプして、その項目が表示されます。

リストボックスを元の位置にとどめたいだけですが、SetSelected他のアイテムを選択するために使用している間、リストボックスが毎回上下に移動することは望ましくありません。

では、メソッドを使用するときにリストボックスとリストボックス対スクロールバーがアイテムにジャンプするのを防ぐにはどうすればよいSetSelectedでしょうか? (上下両方向)

WinAPIの関数を使用してこれを行うことができれば幸いです。

4

2 に答える 2

2

TopIndexを使用して、次のようにトップの表示インデックスを設定してみてください。

//Use this ListBox extension for convenience
public static class ListBoxExtension {
   public static void SetSelectedWithoutJumping(this ListBox lb, int index, bool selected){
     int i = lb.TopIndex;
     lb.SetSelected(index, selected);
     lb.TopIndex = i;
   }
}
//Then just use like this
yourListBox.SetSelectedWithoutJumping(index, true);

また、インデックスのコレクションに対して selected を設定するメソッドを定義し、BeginUpdateandを使用してEndUpdateちらつきを回避することもできます。

 public static class ListBoxExtension {
   public static void SetMultiSelectedWithoutJumping(this ListBox lb, IEnumerable<int> indices, bool selected){
     int i = lb.TopIndex;
     lb.BeginUpdate();
     foreach(var index in indices)
        lb.SetSelected(index, selected);
     lb.TopIndex = i;
     lb.EndUpdate();
   }
}   
//usage
yourListBox.SetMultiSelectedWithoutJumping(new List<int>{2,3,4}, true);

: でBeginUpdateandEndUpdateを使用することもできますが、前述のSetSelectedWithoutJumpingように、複数のインデックスを一緒に選択する必要がある場合は、次のような拡張メソッドを実装するSetMultiSelectedWithoutJumping方が適切で便利です (1 組のBeginUpdateand を使用するだけEndUpdateです)。

于 2013-10-20T16:31:30.027 に答える
0

VB.NET のバージョンを共有したいだけです。

#Region " [ListBox] Select item without jump "

    ' [ListBox] Select item without jump
    '
    ' Original author of code is "King King"
    ' Url: stackoverflow.com/questions/19479774/how-to-prevent-listbox-jumps-to-item
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    '
    ' Select_Item_Without_Jumping(ListBox1, 50, ListBoxItemSelected.Select)
    '
    ' For x As Integer = 0 To ListBox1.Items.Count - 1
    '    Select_Item_Without_Jumping(ListBox1, x, ListBoxItemSelected.Select)
    ' Next

    Public Enum ListBoxItemSelected
        [Select] = 1
        [Unselect] = 0
    End Enum

    Public Shared Sub Select_Item_Without_Jumping(lb As ListBox, index As Integer, selected As ListBoxItemSelected)
        Dim i As Integer = lb.TopIndex ' Store the selected item index
        lb.BeginUpdate() ' Disable drawing on control
        lb.SetSelected(index, selected) ' Select the item
        lb.TopIndex = i ' Jump to the previous selected item
        lb.EndUpdate() ' Eenable drawing
    End Sub

#End Region
于 2013-10-20T17:44:22.320 に答える