How to: Remove all Adorners from an Element

This example shows how to programmatically remove all adorners from a specified UIElement.

Retrieve the adorners on a UIElement

This verbose code example removes all of the adorners in the array of adorners returned by GetAdorners. This example happens to retrieve the adorners on a UIElement named myTextBox. If the element specified in the call to GetAdorners has no adorners, null is returned. This code explicitly checks for a null array, and is best suited for applications where a null array is expected to be relatively common.

Adorner[] toRemoveArray = myAdornerLayer.GetAdorners(myTextBox);
if (toRemoveArray != null)
{
  for (int x = 0; x < toRemoveArray.Length; x++)
  {
    myAdornerLayer.Remove(toRemoveArray[x]);
  }
}
    toRemoveArray = myAdornerLayer.GetAdorners(myTextBox)
If toRemoveArray IsNot Nothing Then
  For x As Integer = 0 To toRemoveArray.Length - 1
    myAdornerLayer.Remove(toRemoveArray(x))
  Next x
End If

Code example

This condensed code example is functionally equivalent to the verbose example shown above. This code does not explicitly check for a null array, so it is possible that a NullReferenceException exception may be raised. This code is best suited for applications where a null array is expected to be rare.

try { foreach (Adorner toRemove in myAdornerLayer.GetAdorners(myTextBox)) myAdornerLayer.Remove(toRemove); } catch { }
Try
        For Each toRemove In myAdornerLayer.GetAdorners(myTextBox)
            myAdornerLayer.Remove(toRemove)
        Next toRemove
Catch
End Try

See also