Nikolas Jíša
Nikolas Jíša

Reputation: 709

WPF C# custom panel

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.

Upvotes: 1

Views: 614

Answers (1)

AkselK
AkselK

Reputation: 2593

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:?

<wpfApplication3:CustomPanel>
   <Button Content="New b"/>
</wpfApplication3:CustomPanel>

If you initiate it like this instead, you'll see that the button stays in place.

public MainWindow()
{
    InitializeComponent();
    Loaded += OnLoaded;
}

private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
    CustomPanel p = new CustomPanel();
    p.Children.Add(new Button(){Content = "T"});
    gr.Children.Add(p);
}

What you can do to avoid this is this:

public CustomPanel()
{
    Initialized += OnInitialized;
}

private void OnInitialized(object sender, EventArgs eventArgs)
{
    var b = new Button { Name = "Button1", Content = "Button1" };
    Children.Insert(0,b);
}

Now you wait until the XAML have replaced the Children object, before you add your button.

Upvotes: 2

Related Questions