Why I am right!

April 25, 2008

SelectionChanged event fires during databinding (Solution)

Filed under: Microsoft, WPF, XAML — Shaun @ 2:54 am

I was having an issue where the SelectionChanged event would fire during WPF DataBinding. While this may be valid, this was not the desired behavior for my application.

Since I could not find anything after a quick Google search I decided to post my workaround. Part of this example was taken from Adam Nathan’s excellent WPF book. Here is some sample code:


<Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="200" Width="300">
        <XmlDataProvider x:Key="dataProvider" XPath="GameStats">
                <GameStats xmlns="">
                    <GameStat Type="Beginner">
                    <GameStat Type="Intermediate">
                    <GameStat Type="Advanced">
        <ListBox ItemsSource="{Binding Source={StaticResource dataProvider}, XPath=GameStat/HighScore}"
                SelectedValue="1203" SelectionChanged="ListBox_SelectionChanged" />


using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication2
  public partial class Window1 : Window
    public Window1()

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
      ListBox listBox = (ListBox)sender;
      if (listBox.IsLoaded)
        Debug.WriteLine("ListBox Selection REALLY Changed.");
        Debug.WriteLine("ListBox Selection Changed but we don't care!");

As you can see I am looking at the IsLoaded property which comes from FrameworkElement. This is not set to true until the data binding is complete. I am not sure if this will work 100% of the time, but it works for my needs.


Create a free website or blog at WordPress.com.