ListBox – Automatically scroll to bottom

In WinForms it was so simple to tell the ListBox to scroll to the buttom.
But in WPF it seems to be rather difficult but it is not.
You can simply create an attached property and once done it will do it for you.

Simply add the attached property to your ListBox

<ListBox ItemsSource="{....}" Extenders:ListBoxExtenders.AutoScrollToEnd="True" />

And here is the source code of the attached property

/// <summary>
  /// This class contains a few useful extenders for the ListBox
  /// </summary>
  public class ListBoxExtenders : DependencyObject
  {
    public static readonly DependencyProperty AutoScrollToEndProperty = DependencyProperty.RegisterAttached("AutoScrollToEnd", typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToEndChanged));

    /// <summary>
    /// Returns the value of the AutoScrollToEndProperty
    /// </summary>
    /// <param name="obj">The dependency-object whichs value should be returned</param>
    /// <returns>The value of the given property</returns>
    public static bool GetAutoScrollToEnd(DependencyObject obj)
    {
      return (bool)obj.GetValue(AutoScrollToEndProperty);
    }

    /// <summary>
    /// Sets the value of the AutoScrollToEndProperty
    /// </summary>
    /// <param name="obj">The dependency-object whichs value should be set</param>
    /// <param name="value">The value which should be assigned to the AutoScrollToEndProperty</param>
    public static void SetAutoScrollToEnd(DependencyObject obj, bool value)
    {
      obj.SetValue(AutoScrollToEndProperty, value);
    }

    /// <summary>
    /// This method will be called when the AutoScrollToEnd
    /// property was changed
    /// </summary>
    /// <param name="s">The sender (the ListBox)</param>
    /// <param name="e">Some additional information</param>
    public static void OnAutoScrollToEndChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
    {
      var listBox = s as ListBox;
      var listBoxItems = listBox.Items;
      var data = listBoxItems.SourceCollection as INotifyCollectionChanged;

      var scrollToEndHandler = new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
          (s1, e1) =>
          {
            if (listBox.Items.Count > 0)
          {
            object lastItem = listBox.Items[listBox.Items.Count - 1];
            listBoxItems.MoveCurrentTo(lastItem);
            listBox.ScrollIntoView(lastItem);
          }
          });

      if ((bool)e.NewValue)
        data.CollectionChanged += scrollToEndHandler;
      else
        data.CollectionChanged -= scrollToEndHandler;
    }
  }

Note that it is similar to the scroll current element into view
So check this out: scroll current item into view

ListBox – Automatically scroll CurrentItem into View

If you are binding a Collection to the ListBox you probably would like the ListBox to automatically scroll the CurrentItem into the view.
Well you can achieve this by doing the following.

Just create a AttachedProperty which listens for the CurrentChanged – Event of the ListBoxItems.
Then it just scrolls the current item into the view.

You can easily add the attached property like this to your ListBox

<ListBox ItemsSource="{...}" IsSynchronizedWithCurrentItem="True" Extenders:ListBoxExtenders.AutoScrollToCurrentItem="True" />

The implementation of the attached property should look like this

  /// <summary>
  /// This class contains a few useful extenders for the ListBox
  /// </summary>
  public class ListBoxExtenders : DependencyObject
  {
    #region Properties

    public static readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached("AutoScrollToCurrentItem", typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged));

    /// <summary>
    /// Returns the value of the AutoScrollToCurrentItemProperty
    /// </summary>
    /// <param name="obj">The dependency-object whichs value should be returned</param>
    /// <returns>The value of the given property</returns>
    public static bool GetAutoScrollToCurrentItem(DependencyObject obj)
    {
      return (bool)obj.GetValue(AutoScrollToCurrentItemProperty);
    }

    /// <summary>
    /// Sets the value of the AutoScrollToCurrentItemProperty
    /// </summary>
    /// <param name="obj">The dependency-object whichs value should be set</param>
    /// <param name="value">The value which should be assigned to the AutoScrollToCurrentItemProperty</param>
    public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)
    {
      obj.SetValue(AutoScrollToCurrentItemProperty, value);
    }

    #endregion

    #region Events

    /// <summary>
    /// This method will be called when the AutoScrollToCurrentItem
    /// property was changed
    /// </summary>
    /// <param name="s">The sender (the ListBox)</param>
    /// <param name="e">Some additional information</param>
    public static void OnAutoScrollToCurrentItemChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
    {
      var listBox = s as ListBox;
      if (listBox != null)
      {
        var listBoxItems = listBox.Items;
        if (listBoxItems != null)
        {
          var newValue = (bool)e.NewValue;

          var autoScrollToCurrentItemWorker = new EventHandler((s1, e2) => OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition));

          if (newValue)
            listBoxItems.CurrentChanged += autoScrollToCurrentItemWorker;
          else
            listBoxItems.CurrentChanged -= autoScrollToCurrentItemWorker;
        }
      }
    }

    /// <summary>
    /// This method will be called when the ListBox should
    /// be scrolled to the given index
    /// </summary>
    /// <param name="listBox">The ListBox which should be scrolled</param>
    /// <param name="index">The index of the item to which it should be scrolled</param>
    public static void OnAutoScrollToCurrentItem(ListBox listBox, int index)
    {
      if (listBox != null && listBox.Items != null && listBox.Items.Count > index && index >= 0)
        listBox.ScrollIntoView(listBox.Items[index]);
    }

    #endregion
  }

Have fun! 🙂

MGLocalizer – A simple way to localize your application

Hello everybody,

since I am usually working with WPF I decided to create my own localizer.
Because I don’t like the standard way to localize a WPF application.

Here is a link to my project: MGLocalizer

I will release the ConfigurationManager soon.
This program automatically generates the csv file for the localizable strings in the .cs file which are located in the given folder.
Such that you don’t have to do it by hand.
Please visit the MGLocalizer – Project page to get more information about the project.

Work on a project simulaniousely with VS 2010 and Expression Blend

If you are using the Beta 1 or 2 of Visual Studio 2010 you may want to use Expression Blend as you designer.
But if you try to open a project created by VS 2010 you will get the following error

The solution “MyProject.sln” is of an unsupported format and may not open correctly. Do you want to open the solution anyway?

Usually it crashes if you click Yes 🙂

The solution for this particular problem is simple.
You just have to set the .NET framework version of your project. Open if with Visual Studio, go to the settings of the project and set a version which is supported by Blend (.Net 3.0 or .Net 3.5).

//EDIT:
I have seen that Microsoft released a preview version of Expression Blend which can be used to work with .Net 4 projects
You can download it here: http://www.microsoft.com/Expression/try-it/default.aspx#PageTop
Note that it only works for .NET 4 projects. For .NET 3 projects you have to use the old version (Blend 3) because at the moment it does not support the old projects!

vmware-authd.exe has a high CPU load… How to fix it?

In the last days I had performance problems with my notebook.
When working with Visual Studio it was very slow and sometimes it was freezing for a while.

After a look in the TaskManager I have seen that the process vmware-authd.exe is using 50% (100% of one core) of the CPU (every 4 or 5 seconds).
First I was confused because I was not running my Virtual Machines so this seems to be a bug.

After using the Process Monitor I have seen that it is looking for this registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WINDOWS NT\CURRENTVERSION\PERFLIB\Disable Performance Counters

After asking Bing i found a few useful threads online where people had the same problem.
Well the solution for the problem is to add the registry key as a DWord and set it to 1

Before I had a CPU usage of 50% every 4-5 Seconds. Now it is never more than 1% 🙂

It hope that the guys from the VMWare team will fix this until the next release

How to assign null to Generics (T)? The solution is Default(T)!

If you are working with generic methods / classes you may have the problem that you can not assign null to a generic type

which means that the following example results in the compile error (Can not convert expression type ‘null’ to return type ‘T’).

private T Foo<T>()
{
    return null;
}

The reason for this compile error is that T could even be a value type. And value types (int, double, etc.) can not be null.
Maybe you also tried a dirty workaround

private T Foo<T>()
{
    return (T)(object)null;
}

But this results in a NullPointer exception. Because it is more or less the same problem as before.
You assign null to a object and then to T which results in the same problem as before.

When i first faced the problem i was not sure how to solved it.
But Google telled me that there exists the default(T) keyword which solves this problem.

private T Foo<T>()
{
   return default(T);
}

I hope that it helps somebody which is in the same situation as I was 🙂

My conclusion about Visual Studio 2010 PRO BETA 2

Hey guys,

I am working since a few days with the beta 2 of Visual Studio 2010 professional (on Windows 7 PRO x64).
And I am really happy with it.

It is stable and fast. In my opinion faster then VS 2008

The fact that you can not deactivate AntiAliasing is not a problem. Other said that especially small fonts are blurry but I can read everything without problems. But there is an extension in the Extension Manager which allows you to deactivate anti aliasing. The name of this extension is “Text Sharp”.
Here is the link to it: Click me!

Moreover it is now in the dark style (similar to Expression Blend) but the main functions are in the same place as in VS 2008.

More information about the product you can find here

In my opinion it is a good decision to change to VS 2010 as soon as it is released.