TextBlock.GetPositionFromPoint raises NullReferenceException

The TextBlock.GetPositionFromPoint raises a NullReferenceException in some cases. This method should return a TextPointer to the text that starts at the given position. In some cases it generates a NullReferenceException instead, which is clearly a bug. The internals of this method looks like:

public TextPointer GetPositionFromPoint(Point point, bool snapToText)
{
  if (this.CheckFlags(Flags.ContentChangeInProgress))
    throw new InvalidOperationException(SR.Get("TextContainerChangingReentrancyInvalid"));

  if (((ITextView)this._complexContent.TextView).Validate(point))
    return (TextPointer) this._complexContent.TextView.GetTextPositionFromPoint(point, snapToText);

  if (snapToText)
    return new TextPointer((TextPointer) this._complexContent.TextContainer.Start);

  return null;
}

The call fails in the TextBlock.GetPositionFromPoint according to the call-stack. The most obvious error is that the _complexContent field isn’t set. After some research, I found out that most methods that rely on this field call TextBlock.EnsureComplexContent() first. This has been neglected in the TextBlock.GetPositionFromPoint method. We cannot call TextBlock.EnsureComplexContent from usercode, because it is a private method. You can get the ContentStart or ContentEnd properties, which will call TextBlock.EnsureComplexContent.

...
var dummy = this.myTextBox.ContentStart;   // WORKAROUND
TextPointer start = this.myTextBox.GetPositionFromPoint(selection.TopLeft, true);
...

Conclusion
This bug should be fixed by Microsoft by adding a call to EnsureComplexContent before it accesses the _complexContent field. It’s fairly easy to prevent the exception, but it might have took you some time to find out about the error and get to this blog.

Response from Microsoft
I have submitted this bug to Microsoft and it is filed under feedback item #478575. Microsoft confirmed it is a bug and it will be fixed when .NET Framework 4 will hit RTM (the current beta still has the bug).

Sample application
Download the sample application.

ScrollViewer always handles the mousewheel

The ScrollViewer control is a convenient control, when the content doesn’t fit on screen and you need some kind of scrolling to make all content accessible. I tend to use the mousewheel to scroll up and down, but this sometimes doesn’t work in WPF applications. It fails when you nest multiple scrollviewers, because the deepest ScrollViewer will always handle the MouseWheel message. Even if there is no vertical scrollbar visible or when it is disabled.

You can see this behaviour when you paste the following code in XamlPad. When you scroll down using the mousewheel and you hit the white area, then it is impossible to scroll further using the mousewheel.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Height="400">
 <ScrollViewer VerticalScrollBarVisibility="Auto">
  <StackPanel>
    <Border BorderBrush="Black" BorderThickness="1" Width="400" Height="200" Background="Red"/>
    <ScrollViewer VerticalScrollBarVisibility="Disabled">
      <Border BorderBrush="Black" BorderThickness="1" Width="400" Height="200" Background="White"/>
    </ScrollViewer>
    <Border BorderBrush="Black" BorderThickness="1" Width="400" Height="200" Background="Blue"/>
  </StackPanel>
</ScrollViewer>
</Page>

It’s a bad idea to have two vertical scrollbars that are nested, but sometimes you use a control that has a ScrollViewer inside its template. Because you have wrapped the control in your own ScrollViewer, the scrollbars will never be visible. But because it does handle the MouseWheel messages, the mousewheel will stop scrolling when the mouse hovers over it. This is very annoying to the end-user.

I used .NET Reflector to check how the MouseWheel message was handled. It looks like this:

protected override void OnMouseWheel(MouseWheelEventArgs e)
{
  if (!e.Handled && this.HandlesMouseWheelScrolling)
  {
    if (this.ScrollInfo != null)
    {
      if (e.Delta < 0)
        this.ScrollInfo.MouseWheelDown();
      else
        this.ScrollInfo.MouseWheelUp();
    }
    e.Handled = true;
  }
}

As you can see, it’s quite easy to prevent the MouseWheel message from being processed and that is to set the HandlesMouseWheelScrolling to false, when the vertical scrollbar is hidden or invisible. Unfortunately, Microsoft decided to mark this property as internal, so it isn’t accessible. This property is used exclusively by the TextBox control (it uses a ScrollViewer too), that disables the handling of the MouseWheel message of the internal ScrollViewer. The result is that a TextBox doesn’t block vertical scrolling when using the mousewheel.

The problem can also be solved a different way, but this requires is us to subclass the ScrollViewer:

public class ExtScrollViewer : ScrollViewer
{
  private ScrollBar verticalScrollbar;

  public override void OnApplyTemplate()
  {
    // Call base class
    base.OnApplyTemplate();

    // Obtain the vertical scrollbar
    this.verticalScrollbar = this.GetTemplateChild("PART_VerticalScrollBar") as ScrollBar;
  }

  protected override void OnMouseWheel(MouseWheelEventArgs e)
  {
    // Only handle this message if the vertical scrollbar is in use
    if ((this.verticalScrollbar != null) && (this.verticalScrollbar.Visibility == Visibility.Visible) && this.verticalScrollbar.IsEnabled)
    {
      // Perform default handling
      base.OnMouseWheel(e);
    }
  }
}

The new MouseWheel handling doesn’t do anything when the vertical scrollbar is either invisible or disabled. The drawback of this approach is that you need to use a custom ScrollViewer, instead of the default ScrollViewer. You can do this pretty easy for your own controls, but if you have third party controls that you don’t control, then this won’t work.

Sebastien Lambla describes a method on his blog that allows you to change the characteristics of the default ScrollViewer. Use whatever you like best.

I have submitted this bug with Microsoft. You can track it here.

Properties and data binding

Every WPF/Silverlight programmer that writes it’s own business objects or custom controls either uses dependency properties or implements the INotifyPropertyChanged interface. Both have their own advantages and disadvantages:

Dependency properties:

  • Full support for databinding (read and write).
  • Only accessible from the thread that created the object.
  • WPF/Silverlight dependant, so requires additional assemblies at runtime and requires .NET 3.0 (or later).
  • Support for attached dependency properties, so you can extend other DependencyObject derived types with your class’ properties.
  • Some additional plumbing necessary, which is less trivial then normal .NET properties (i.e. respond to property updated).

Normal .NET properties (with INotifyPropertyChanged support):

  • Only suitable as a source in WPF databinding.
  • Properties can be read and write from an arbitrary thread (of course, you need some thread synchronization to avoid problems).
  • Not related to a specific .NET technology, so it can be used in any architecture.
  • Additional plumbing necessary to fire the PropertyChanged event.

You might wonder which kind of property you need to use. You can use the following guidelines:

  • If you expect to use to instantiate the class in XAML, then stick to dependency properties. This makes databinding a lot easier.
  • If you expect to use the class also to be used outside the WPF/Silverlight environment, then .NET properties are the way to go.

Normal .NET properties can be written in a very convenient way, like:

public string FullName { get; set; }

But, if you want to support INotifyPropertyChanged, then you need at least the following code:

private string _fullName;
public string FullName
{
 get { return this._fullName; }
 set
 {
  if (this._fullName != value)
  {
   this._fullName = value;
   if (this.PropertyChanged != null)
     this.PropertyChanged(this, new PropertyChangedEventArgs("FullName"));
  }
 }
}

As you can see, the INotifyPropertyChanged support adds a lot of code to each property. Even worse… It is prone to errors, because you need to specify the property name as a string. These kind of properties are often copy/pasted, so beware of mistakes (it might raise issues when you are refactoring the code). I created a Visual Studio macro that generates this plumbing for me to avoid these mistakes. But still… It’s a lot of work and a good programmer avoids repeating tasks.

It would be nice if MS added a special .NET attribute or keyword to C# to generate the plumbing automatically at compile time. Unfortunately, there is no such keyword and it hasn’t been announced for the upcoming C# 4.0 release.

Update Controls
Recently, I listened to a podcast from Polymorphic Podcasts that had the appealing title “Update Controls may render INotifyPropertyChanged obsolete”. More information can be found on CodePlex. Although sceptical, I listened to the podcast and decided to take a deeper look into this technology.

The update controls is a library written by Michael L. Perry and it uses a completely different approach to track property changes. It keeps track of the inter property dependencies, so it knows which properties have to be updated when a property is changed. It uses a quite sophisticated algorithm to determine the dependencies, but this is all completely transparent to the programmer.

Unfortunately, this library also needs additional plumbing in your properties, which is even more then when implementing IPropertyChanged:

private string _fullName;
private Dependent _indFullName = new Dependent();

public string FullName
{
 get { this._indFullName.OnGet(); return this._fullName; }
 set { this._indFullName.OnSet(); this._fullName = value; }
}

The dependencies are tracked during the execution of the OnGet and OnSet methods. There is also a XAML markup extension that also contains the required plumbing for dependency tracking. The major advantage of this approach above the INotifyPropertyChanged and regular WPF depenency properties is that dependant properties are automatically updated.

Suppose the following example:

class Person
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

When you are using dependency properties or implement INotifyPropertyChanged then you need some kind of logic that also updates the fullname, when you change the first and/or lastname. When using the update controls, this is done automatically. The update controls know about it, because it sees that you call the FirstName and LastName properties inside the FullName getter. Quite clever…

As always, there is a catch… You need to go through the special XAML markup extension to make sure the value is updated. Normal WPF applications would use the following binding:

<TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/>
<Label Text="{Binding FullName}"/>

When using updatecontrols, this doesn’t work. Although everything compiles and runs just fine, the FullName is never updated. To WPF it is an ordinary property, so it expects a PropertyChanged event and it will never receive it. When using the update controls you need to use the special XAML markup extension, like this:

<TextBox Text="{uc:Update FirstName}"/>
<TextBox Text="{uc:Update LastName}"/>
<Label Text="{uc:Update FullName}"/>

It seems like a minor change, but you need to know in your XAML code if your underlying object uses update controls or if it uses the old-style dependency properties or INotifyPropertyChanged. I consider this a major disadvantage and I have decided to stick with the WPF dependency properties and the INotifyPropertyChange interface.

The update controls might be very valuable, when you’re using a lot of properties that depend on eachother. In those special cases it might be convenient to have the automatic update functionality.

Using PostSharp to implement INotifyPropertyChanged
PostSharp is a tool that can be used to inject code. It is extensible and when you combine PostSharp with PropFu, then you can generate the PropertyChanged automatically.

[NotifyPropertyChanged]
public class Person : INotifyPropertyChanged
{
 public string Name { get; set; }
 public event PropertyChangedEventHandler PropertyChanged;

 [OnPropertyChanged]
 private void OnPropertyChanged(string propertyName)
 {
  if (this.PropertyChanged != null)
   this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }
}

When you mark the class with the NotifyPropertyChanged attribute, then it will raise the PropertyChanged event for all public properties. You need to implement a method that will actually raise the property and mark it with the OnPropertyChanged attribute. After running PostSharp the class will be emitted like this:

[NotifyPropertyChanged]
public class Person : INotifyPropertyChanged
{
 private string _name;
 public string Name
 {
  get { return this._name; }
  set
  {
   if (this._name != value)
   {
    this._name = value;
    this.OnPropertyChanged("Name");
  }
 }
 public event PropertyChangedEventHandler PropertyChanged;

 [OnPropertyChanged]
 private void OnPropertyChanged(string propertyName)
 {
  if (this.PropertyChanged != null)
   this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }
}

When you install PostSharp it will update your Visual Studio configuration, so it will automatically invoke PostSharp at the end of each build. Of course, you can disable this and call PostSharp yourself.

I think this is a fairly elegant solution. PostSharp has a lot of additional functionality, so I suggest to take a further look at it.

ListView may leak with ImageLists

Today, I encountered a problem with WinForm’s ListView imagelist. When you assign a global imagelist to the listview, then the listview will remain in memory forever. When the ListView references other objects, then these objects won’t be collected too and you might end up with a huge memory leak.

When does this occur?
ListViews won’t be collected until the associated imagelist(s) is collected, when you don’t reset the SmallImageList, LargeImageList or StateImageList properties yourself.

Why does this occur?
The LargeImageList property is implemented like this:

public ImageList LargeImageList
{
 get { return this.imageListLarge; }
 set
 {
  if (value != this.imageListLarge)
  {
   // Unsubscribe from the old image list events
   if (this.imageListLarge != null)
   {
    this.imageListLarge.RecreateHandle -= LargeImageListRecreateHandle;
    this.imageListLarge.Disposed -= DetachImageList;
    this.imageListLarge.ChangeHandle -= LargeImageListChangedHandle;
   }

   // Save new imagelist
   this.imageListLarge = value;

   // Subscribe to the new image list events
   if (value != null)
   {
    value.RecreateHandle += new EventHandler(LargeImageListRecreateHandle);
    value.Disposed += new EventHandler(DetachImageList);
    value.ChangeHandle += new EventHandler(LargeImageListChangedHandle);
   }

   // Update the underlying imagelist,
   // if the control is already created
   if (base.IsHandleCreated)
   {
    IntPtr imageListHandle = (value==null)?IntPtr.Zero:value.Handle;
    base.SendMessage(LVM_SETIMAGELIST, IntPtr.Zero, imageListHandle);
    if (this.AutoArrange && !this.listViewState[4])
     this.UpdateListViewItemsLocations();
   }
  }
 }
}

The implementation of SmallImageList and StateImageList are similar. You can clearly see that the ListView subscribes to the following three events of the ListView:

  • The RecreateHandle event is raised when the ImageList handle is recreated, because some of the properties have changed, that require that the underlying ImageList object to be recreated. The ListView responds to this event by setting the new ImageList to the underlying ListView object.
  • The Disposed event is raised when the ImageList is disposed. The ListView responds to this event by resetting the LargeImageList property to NULL.
  • The ChangeHandle event is an internal (and undocumented) event from the ImageList that is raised, when the ImageList is changed (i.e. adding or removing an image from the imagelist). The ListView responds to this event by setting the item images. Note that this event is only subscribed to for the LargeImageList property.

The basic idea of the garbage collector is that objects that aren’t referenced anymore are collected. As long as you reference an object it will stay alive. Subscribing to an object means that you reference the object via the event handler delegate. So, before the ListView can be collected, the reference to the imagelists should be removed by setting the properties to NULL. This will effectively unsubscribe from the three events.

When the ListView is disposed, then it should make sure that it unsubscribe from these events to prevent that the subscription keeps the ListView alive. The Dispose method is implemented like this:

protected override void Dispose(bool disposing)
{
 if (disposing)
 {
  // Reset small imagelist
  if (this.imageListSmall != null)
  {
   this.imageListSmall.Disposed -= DetachImageList;
   this.imageListSmall = null;
  }

  // Reset large imagelist
  if (this.imageListLarge != null)
  {
   this.imageListLarge.Disposed -= DetachImageList;
   this.imageListLarge = null;
  }

  // Reset state imagelist
  if (this.imageListState != null)
  {
   this.imageListState.Disposed -= DetachImageList;
   this.imageListState = null;
  }

  // [some other code removed]
  // ...

  // Call base class
  base.Dispose(disposing);
 }
}

As you can see, this method only unsubscribes from the Disposed event, but not from the imagelist’s RecreateHandle and ChangeHandle events. The garbage collector will keep the ListView alive, until the associated imagelists are collected. When you use a global imagelist, then this will never occur and each instance of the ListView that uses the imagelist will remain alive forever.

Microsoft can easily fix this problem by rewriting the Dispose method like this:

protected override void Dispose(bool disposing)
{
 if (disposing)
 {
  // Reset imagelists (note that we set the property, not the attribute)
  this.ImageListSmall = null;
  this.ImageListLarge = null;
  this.ImageListState = null;

  // [some other code removed]
  // ...

  // Call base class
  base.Dispose(disposing);
 }
}

For now the only thing that you can do is to make sure you reset the imagelist yourself before your ListView is disposed.

So how about TreeViews?
A TreeView also uses an imagelist, so it would make sense that the same problem exists there. Fortunately, the TreeView is fine, because the implementation uses two special methods to subscribe and unsubscribe from the three events. The Dispose method of the TreeView calls the unsubscribe method, so the TreeView is fine.

Sample application
I have created a sample application that clearly demonstrates the problem. I needed to override the ListView class to make sure I could count its instances, but it doesn’t have any other side effects.

To illustrate the problem, start the application and press the “Create form” button. This will create a ListView and populates it with some items. When you refresh the counters you’ll see that you have one instance and one active instance (this means an instance that hasn’t been disposed yet). If you close the form and refresh the counters again, then you’ll see that there is no active instance anymore, but this is still a ListView instance. This means that the form has been disposed, but hasn’t been collected. You can try this over and over, but you will never see the number of ListView instances drop.

When you enable the “Reset imagelists when disposing” checkbox in the main form, then the properties are reset and you’ll see that the number of instances will stay in sync with the number of active instances.
Download the sample application.

Response from Microsoft
I have submitted this bug into the MSDN Managed Newsgroups and the Microsoft Feedback website. Microsoft acknowledges this to be a problem and, when it fits the schedule, it will be fixed. The recently released .NET Framework 4 Beta 1 doesn’t include the fix.

Microsoft updated the status to resolved (closed) on June 7th, 2009, but didn’t provide additional information how and when the fix will be available.