How to prevent flickering in ListView when updating a single ListViewItem's text?

前端 未结 10 2234
囚心锁ツ
囚心锁ツ 2020-11-27 04:56

All I want is to update an ListViewItem\'s text whithout seeing any flickering.

This is my code for updating (called several times):

listView.BeginUp         


        
10条回答
  •  天命终不由人
    2020-11-27 05:41

    The accepted answer works, but is quite lengthy, and deriving from the control (like mentioned in the other answers) just to enable double buffering is also a bit overdone. But fortunately we have reflection and can also call internal methods if we like to (but be sure what you do!).

    Be encapsulating this approach into an extension method, we'll get a quite short class:

    public static class ControlExtensions
    {
        public static void DoubleBuffering(this Control control, bool enable)
        {
            var method = typeof(Control).GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic);
            method.Invoke(control, new object[] { ControlStyles.OptimizedDoubleBuffer, enable });
        }
    }
    

    Which can easily be called within our code:

    InitializeComponent();
    
    myListView.DoubleBuffering(true); //after the InitializeComponent();
    

    And all flickering is gone.

    Update

    I stumbled on this question and due to this fact, the extension method should (maybe) better be:

    public static void DoubleBuffered(this Control control, bool enable)
    {
        var doubleBufferPropertyInfo = control.GetType().GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
        doubleBufferPropertyInfo.SetValue(control, enable, null);
    }
    

提交回复
热议问题