Tuesday, October 20, 2009

NullReferenceException on String.IsNullOrEmpty in WPF

I really like the power of what can be done in WPF, but every time I turn around there is some trivial thing that gets in my way of being productive. This time it is a NullReferenceException being thrown when I do a String.IsNullOrEmpty check on the Label text (Content) in a button click event.

   1: If PlayButtonText = "Play" Then
   2:    SetValue(PlayButtonTextProperty, "Pause")
   3:    ' NullReferenceException thrown on following line
   4:    If String.IsNullOrEmpty(lblStartTime.Content.ToString) Then
   5:       lblStartTime.Content = DateTime.Now
   6:    End If
   7:    myTimer.Start()
   8:  
   9: Else
  10:    SetValue(PlayButtonTextProperty, "Play")
  11:    myTimer.Stop()
  12: End If

A similar bug was first reported in 2006 .Net 2.0 when used in a loop in a console app with an empty construct, and was subsequently fixed. It seems odd that I would experience a similar bug (or feature, if that is what it would be classified as) that has yet to be fixed as of .Net 3.5 SP1 in Visual Studio 2008. My usage above does not seem to be that uncommon.


Workaround


Replace the Label control with a TextBlock control, obviously replacing the lblStartTime.Content property with lblStartTime.Text property since there is no Content property on the TextBlock control.


Josh Smith wrote a good blog post explaining the differences between a WPF Label control vs. a TextBlock control.

No comments: