1

我在 WPF 窗口中使用 Canvas 来显示 UserControl。我不想在 Canvas 中添加相同的 UserControl。

我怎样才能做到这一点?

目前我做过..

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);
            }
        }
    }
}

并像这样添加一个 UserControl

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

它对我有用,但是当我添加其他控件时

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

它抛出一个名为的异常

枚举数无效,因为集合已更改。

4

2 回答 2

2

该错误是由于您在循环遍历枚举的过程中(在foreach内部)修改了枚举。只需要使用一种不会改变枚举的方法:

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);
}
于 2012-04-24T22:12:59.417 回答
0

或者更简单地说

if (JIMSCanvas.Children.Any(c => c.Uid == ctrl.Uid)
{
   MessageBox.Show("Already"); 
}
else
{
   JIMSCanvas.Children.Add(ctrl); 
}
于 2012-04-25T10:25:41.023 回答