The order in which properties are set is undefined. It might be the order in which reflection returns the properties to the designer or it could be alphabetically. The only ordering guarantee that the designer gives is that all controls will be created before any property values are assigned. Nevertheless this is a common issue.
Enter ISupportInitialize. This interface's sole purpose in life is to allow components to delay initialization until all properties have been set. If a component implements this interface then you'll see a call to BeginInit after the component is created. This is a single to the component that a bunch of properties are about to be set and the component should wait until later to do any work against the properties. When EndInit is called (after all components' properties have been set) then the component can react to the property changes.
To be honest though this interface is really designed for more complex scenarios then the one you describe. In a case like yours the problem is that you are assuming that the selected item is in the list of items. Does it really matter whether it is nor not? All you're likely to do is set an internal field and then perhaps raise an event. However it doesn't make any sense to raise an event while you are initializing.
Most controls (in this situation) will use the HandleCreated property to determine if the control has actually been created yet. Controls aren't technically created (on the Windows side) until after initialization is complete. If HandleCreated is true then you can assume that all initialization is complete and the specified item should be available. If it isn't then just set the internal field. Later when you actually create the control OnHandleCreated you can look at the selected item property and, if set, raise the appropriate event. This is how controls like the treeview work and is a little more efficient then using ISupportInitialize.
public CustomTabStrip SelectedItem
{
get { return m_SelectedItem; }
set
{
if (HandleCreated && (m_SelectedItem != value))
{
//Confirm the item is in the list
m_SelectedItem = value;
//Raise an event
} else
m_SelectedItem = value;
}
}
protected override void OnHandleCreated ( )
{
base.OnHandleCreated();
if (m_SelectedItem != null)
{
//Confirm item in list
//Raise an event
};
}
Michael Taylor - 9/14/07
http://p3net.mvps.org