I want to create a user control which would work the same way as a classic Panel (or Canvas rather) control expect that I want to have there some default Buttons which the user won’t be able to remove.
I tried this:
namespace WpfApplication1
{
public class CustomPanel : Canvas
{
public CustomPanel()
{
Button b = new Button();
b.Name = "Button1";
b.Content = "Button1";
this.Children.Add(b);
}
}
}
It works, but when I compile it and create an instance of CustomPanel in the designer and then try to insert another item the Button created in constructor gets deleted.
Is this the correct approach at all or is there a better (more effective/elegant) way then modfying the constructor?
Thanks in advance for any efforts.
Your problem is that you add the Button to the Children object, in the constructor, and then replace the whole Children object when you instance it in XAML.
I’m guessing your XAML looks like this:?
If you initiate it like this instead, you’ll see that the button stays in place.
What you can do to avoid this is this:
Now you wait until the XAML have replaced the Children object, before you add your button.