Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight ComboBox and SelectedItem

I have the following scenario:

1 List which contains the months of the year:

public List<String> Months
{
    get
    {
        return m_Months;
    }
}


m_Months = new List<String>();

for (int i = 1; i <= 12; i++)
{
    DateTime date = new DateTime(1900, i, 1);
    m_Months.Add(date.ToString("MMM"));
}

1 ComboBox whose ItemsSource is bound to the Months-list and whose SelectedIndex is bound to the property Month, which is a string:

public string Month
        {
            get
            {
                return m_Month;
            }
            set
            {
                if (value != m_Month)
                {
                    m_Month = value;
                    NotifyPropertyChanged("Month");
                }
            }
        }

<ComboBox SelectedItem="{Binding Month, Mode=TwoWay}" ItemsSource="{Binding Months}" />

When I set the Year from the codebehind, i.e. Month = "May", this is properly propagated to the ComboBox, and the getter for Month is accessed, but the ComboBox doesn't show 'May' as it's selected item.

I'd like to know: is this a bug in Silverlight 3? It works fine when I use the RadComboBox from Telerik.

Cheers, Frances

like image 525
user112889 Avatar asked Jun 09 '09 02:06

user112889


1 Answers

Thanks for your reply. Tried your suggestion already and get the same results. However, I've just had a Homer Simpson moment (Dôh!) and found out that I set the Month before the ComboBox sets it's ItemsSource.

Strange, though, that the RadComboBox does everything correctly. Maybe it retrieves the SelectedItem again when the ItemsSource changes.

EDIT:

OK, I just literally fell off my chair with amazement. Apparently, SL3 still has some bugs that need fixing. Feast your eyes on the following...

This doesn't work:

<ComboBox SelectedItem="{Binding Month, Mode=TwoWay}" ItemsSource="{Binding Months}" />

And this does:

<ComboBox ItemsSource="{Binding Months}" SelectedItem="{Binding Month, Mode=TwoWay}" />

See the tiny difference? As long as I set the ItemsSource before the SelectedItem in the XAML, all is well in the world. Wowee, I never knew XAML was parsed linearly!

like image 105
user112889 Avatar answered Oct 15 '22 11:10

user112889