title: DragEnter & DragLeave: Avoid nasty flickering on custom drag preview
body: <p>I've implemented a little WPF app to drag an animal from the shop in to my barn. ;-)</p>
  
  <p>I'm using:</p>
  
  <ul>
  <li>MVVMlight and its <code>EventToCommand</code> behaviors</li>
  <li>The animal is a simple <code>Border</code> listening on <code>MouseDown</code></li>
  <li>The barn is an <code>ItemsControl</code> bound to an <code>ObservableCollection</code> of the ViewModel. It listens to 3 events:
  <ul>
  <li><code>DragEnter</code> (adds a dummy animal into the <code>ObservableCollection</code> to preview where the animal is placed in the barn)</li>
  <li><code>DragLeave</code> (removes the dummy animal if the animal isn't dropped)</li>
  <li><code>Drop</code> (sets the animal to the designated place in the barn).</li>
  </ul></li>
  </ul>
  
  <p>Sorry. I don't have the reputation to upload images. So I try some ascii arts (try to image dragging the donkey into the barn): </p>
  
  <pre><code>Shop   | Barn
  -------------------------
  Mouse  | [Mouse] [Dog] 
  Cat    | [.]
  Dog    |  ^
  Donkey-|--|
  </code></pre>
  
  <p><strong>Here's the problem:</strong></p>
  
  <p>If I drag an animal into the barn onto it's designated space (the preview dummy):</p>
  
  <ol>
  <li><code>DragLeave</code> removes the dummy item and immediately the</li>
  <li><code>DragEnter</code> will be fired to redraw the dummy item. Goto step 1.</li>
  </ol>
  
  <p>An inifite loop. The flickering is up and running!</p>
  
  <p><strong>Does anyone know a nice little workaround?</strong></p>
  
  <p>So here's the code of my ViewModel:</p>
  
  <pre class="lang-cs prettyprint-override"><code>private string _dummy;
  public ObservableCollection&lt;string&gt; Animals { get; private set; }
  
  private void StartDrag(FrameworkElement element)
  {
      var animal = element.DataContext as string;
      if (animal == null) return;
      System.Windows.DragDrop.DoDragDrop(element, animal, DragDropEffects.Copy);
  }
  
  private void PreviewDrop(DragEventArgs args)
  {
      if (args.Data.GetDataPresent(typeof (string)))
          AddDummy();
  }
  
  private void StopDrop(DragEventArgs args)
  {
      RemoveDummy();
  }
  
  private void Drop(DragEventArgs args)
  {
      var animal = args.Data.GetData(typeof (string)) as string;
      if (animal == null) return;
  
      RemoveDummy();
      Animals.Add(animal);
  }
  
  private void RemoveDummy()
  {
      if (_dummy == null) return;
      Animals.Remove(_dummy);
      _dummy = null;
  }
  
  private void AddDummy()
  {
      if (_dummy != null) return;
      _dummy = ".";
      Animals.Add(_dummy);
  }
  </code></pre>
  
  <p>Thanks for your help</p>
  
  <p>Marcel</p>