Search code examples
c#user-controlsinvalidation

UserControl Invalidate() method. How to properly invalidate the child controls in a UserControl


I have created my UserControl class and everything works as it should. Just wondering what method Invalidate does. It actually does not invalidate controls in my class, and I have not found any effects when it is called. Could anyone explain what this method does in the UserControl classes.

enter image description here


Solution

  • To make a UserControl Invalidate all nested controls you need to call a special overload of Invalidate(invalidateChildren):

    yourUserControl.Invalidate(true);
    

    Invalidates a specific region of the control and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.

    Note the remarks:

    Remarks

    Calling the Invalidate method does not force a synchronous paint; to force a synchronous paint, call the Update method after calling the Invalidate method. When this method is called with no parameters, the entire client area is added to the update region.

    Update

    If you want to call this from a thread other than the UI thread you need to use Invoke, maybe like this:

    public delegate void InvalidateUC();
    public InvalidateUC myInvalidateDelegate;
    
    public void InvalidateMethod()
    {
        yourUserControl1.Invalidate(true);
    }
    

    Now, after doing

    myInvalidateDelegate = new InvalidateUC(InvalidateMethod);
    

    You can call this from the other thread

    yourForm.yourUserControl1.Invoke(myInvalidateDelegate);
    

    note that if you are not quite sure whether the call actually comes from a non-ui thread you can (and should) add the condition

    if (yourForm.yourUserControl1.InvokeRequired)..