Sunday, March 28, 2010

Silverlight TabControl SelectionChanged

This is a strange behaviour I encountered with the Silverlight TabControl SelectionChanged event.
My XAML is defined as such:
<basics:TabControl x:Name="ReportTabs" SelectionChanged="ReportTabs_SelectionChanged" >
...
</basics:TabControl >

In my cs file, I have defined the corresponding ReportTabs_SelectionChanged function.
private void ReportTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabItem item = ReportTabs.SelectedItem as TabItem;
if (item == tabAdvancedRpt)
{
Page1Panel.Visibility = Visibility.Visible;
Page2Panel.Visibility = Visibility.Collapsed;
}
}

This will give me initialisation error when I try to run the Silverlight project.
This is because on the first hit of this SelectionChanged event, the TabControl has not been initialised. As such, there is a need to check if ReportTabs == null.

Why does the SelectionChanged event get hit even when the control is not initialised? Strange...

1 comment:

  1. Thank you so much my friend,

    I have been banging my head with this for 4 days.

    And like you, i think this is extremely strange and should not be the case. but alas, it is.

    The event is being fired when none of the controls is initialized yet.

    ReplyDelete