Kishore Kumar
Kishore Kumar

Reputation: 12864

Avoiding adding Same UserControl in Canvas in WPF?

I am using Canvas in WPF Window to show UserControl. I dont want to add the same UserControl in the Canvas.

How can i do that?

Current i have done..

private void OpenChild(UserControl ctrl)
{            
    ctrl.Uid = ctrl.Name;
    if (JIMSCanvas.Children.Count == 0)
    {                
        JIMSCanvas.Children.Add(ctrl);
    }
    else
    {
        foreach (UIElement child in JIMSCanvas.Children)
        {
            if (child.Uid == ctrl.Uid)
            {
                MessageBox.Show("Already");
            }
            else
            {
                JIMSCanvas.Children.Add(ctrl);
            }
        }
    }
}

and adding a UserControl like this

OpenChild(new JIMS.View.Ledger());

It works for me but when i add an other Control like

OpenChild(new JIMS.View.Stock());

Its throwing an exception called

The enumerator is not valid because the collection changed.

Upvotes: 1

Views: 708

Answers (2)

Dean Chalk
Dean Chalk

Reputation: 20451

Or more simply

if (JIMSCanvas.Children.Any(c => c.Uid == ctrl.Uid)
{
   MessageBox.Show("Already"); 
}
else
{
   JIMSCanvas.Children.Add(ctrl); 
}

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102743

The error is due to the fact that you're modifying the enumeration while in the process of cycling through it (inside the foreach). Just have to use a method that doesn't alter the enumeration:

bool alreadyExists = false;
UIElement existingElement = null;
foreach (UIElement child in JIMSCanvas.Children)
{
    if (child.Uid == ctrl.Uid)
    {
        alreadyExists = true;
        existingElement = child;
    }
}
if (alreadyExists)
{
    MessageBox.Show("Already");
    existingElement.Visibility = System.Windows.Visibility.Visible;
}
else
{
    JIMSCanvas.Children.Add(ctrl);
}

Upvotes: 2

Related Questions