Problem described:
1. I am creating a user control (UC1) inherited from UltraTextEditor
2. In the constructor of UC1 I add an EditoButton (key=MyKey) to the ButtonsRight collection.
3. I place UC1 on a Form, save and close.
4. I reopen the Form and get an error because of a duplicate key (MyKey).
5. If I look at the Designer code, the Form itself is also adding an EditorButton to UC1 with the same key (MyKey). I did not expect this behavior.
What am I missing? What is the best approach to this problem?
Thanks.
The problem is that the button gets serialized along with the form at design-time. So your constructor adds the button, but then the Visual Studio tries to add it in again when it loads the form.
So, instead of adding the button in the constructor, you have to add your button after the control has finished deserializing and check to see if the button is already there before you add it. Either that, or you have to add the button in a place that only gets called once when the control is initially created and not every time it is deserialized.
Try overring the OnCreateControl method and see if that works.
If not, try OnEndInit. I'm pretty sure that will work.