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:

Window1.xaml

<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">
    <Window.Resources>
        <XmlDataProvider x:Key="dataProvider" XPath="GameStats">
            <x:XData>
                <GameStats xmlns="">
                    <GameStat Type="Beginner">
                        <HighScore>1203</HighScore>
                    </GameStat>
                    <GameStat Type="Intermediate">
                        <HighScore>1089</HighScore>
                    </GameStat>
                    <GameStat Type="Advanced">
                        <HighScore>541</HighScore>
                    </GameStat>
                </GameStats>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource dataProvider}, XPath=GameStat/HighScore}"
                SelectedValue="1203" SelectionChanged="ListBox_SelectionChanged" />
    </Grid>
</Window>

Window1.xaml.cs

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

namespace WpfApplication2
{
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
    }

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      ListBox listBox = (ListBox)sender;
      if (listBox.IsLoaded)
      {
        Debug.WriteLine("ListBox Selection REALLY Changed.");
      }
      else
      {
        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.

Advertisements

Create a free website or blog at WordPress.com.