title: wpf: Maintain rectangle fill color on mouseenter / mouseleave
body: <p>I have a <code>Grid</code> control to which I am dynamically adding rows that look as follows:</p>
  
  <p><a href="https://i.stack.imgur.com/jvzXj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jvzXj.jpg" alt="enter image description here"></a></p>
  
  <p>I want to highlight the row that has the mouse cursor over it. I'm currently doing this by adding a <code>Rectangle</code> to the row as the background, and changing its <code>Fill</code> property on <code>MouseEnter</code> and <code>MouseLeave</code>.</p>
  
  <pre class="lang-c# prettyprint-override"><code>Rectangle rect = new Rectangle();
  Grid.SetRow(rect, rowNum);
  Grid.SetColumn(rect, colNum);
  Grid.SetColumnSpan(rect, dataGrd_.ColumnDefinitions.Count);
  rect.Fill = new SolidColorBrush(Colors.White);
  rect.MouseEnter += Rect_MouseEnter;
  rect.MouseLeave += Rect_MouseLeave;
  dataGrd_.Children.Add(rect);
  
  private void Rect_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
  {
      (sender as Rectangle).Fill = new SolidColorBrush(Colors.White);
  }
  
  private void Rect_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
  {    
      (sender as Rectangle).Fill = new SolidColorBrush(Colors.Yellow);
  }
  </code></pre>
  
  <p>The problem is that when the mouse moves over one of the controls in the foreground of the row, the <code>MouseLeave</code> event is triggered and the highlighting is lost.</p>
  
  <p>Is there a way to have the highlighting persist as long as the mouse is within the bounds of the <code>Rectangle</code>, even if it's over a control that is in the foreground?</p>
  
  <p>Also, the <code>MouseEnter</code> event isn't firing when the mouse enters the row, but is over a <code>Label</code> or another control. I suppose I can add event handlers to all of the controls, but that sounds excessive.</p>
  
  <p>Since I'm adding these rows dynamically, I'm really only interested in code behind solutions, unless there's a way to achieve what I'm after in XAML.</p>