Why SelectedValue does not show up on initial page load in Silverlight for ComboBox Control?

One of my colleague ran into this problem last week and thought of sharing the problem solution and one excellent side benefit. Let me explain the problem. We have a combo box, which have list of years. Once the years property is loaded, we set the maximum value in the years field as the default selected year and show that year. Very simple, done it bunch of times no biggie. Also I want to point out here that what I have been talking about for my last couple of posts, we can  identify and resolve lot of problems with ‘Design Time Data’ than waiting for it to run.

For the people who wants to know the solution rather than all the explanation, the SlectedValue data type and ItemsSource data type were mismatching that’s why selected item did not show up in the first time load. Let me show you how to duplicate and fix the problem without even running the program.

First lets create the interface for run time and design time view model (best practices). I copied the code from the program that was failing and the properties look like the following in IMainViewModel.cs

public interface IMainViewModel
{
    List<Int16> Years { get; }
    int SelectedYear { get; }
}

you will notice that combo box going to be bound to Years of type Int16 while the selected year is int, that was the problem but at that time of writing the code I did not know that. With that interface, let me implement the Design time view model ‘DesignMainViewModel.cs’ as

public class DesignMainViewModel : IMainViewModel
{
    public List<Int16> Years
    {
        get
        {
            List<Int16> years = new List<Int16>();
            years.Add(2011);
            years.Add(2010);
            return years;
        }
    }

    public int SelectedYear
    {
        get
        {
            return 2011;
        }
    }
}

Lets look at the XAML

        <ComboBox ItemsSource="{Binding Years}" SelectedValue="{Binding SelectedYear, Mode=TwoWay}" Grid.Row="1"/>

Now if you look at the design time gird, you will see the selected year is blank

image

Here itself I know there is a problem with selected year since it is not showing 2011. Now looking at the definition on IMainViewModel, instead of using two different data types, if you would switch them to same data type and change the implementation in Interface, design time and run time view model, your design screen would look like the following

image

see 2011 shows up. The solution in here is that, when you are binding a collection to a combo box, make sure the data type of the property bound to SelectedValue also have the same data type.

The best part of it all, I was able to identify the problem during the design time and was able to fix it also at the design time.

Advertisements