2012-04-24 26 views
1

我在WPF窗口中使用畫布來顯示UserControl。 我不想在畫布中添加相同的用戶控件。避免在WPF中的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); 
      } 
     } 
    } 
} 

,加入這樣的

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

這對我的作品,但一個用戶控件,當我添加其他控件像

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

其拋出一個叫做

的例外

枚舉器無效,因爲集合已更改。

回答

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

但不是顯示的消息我想改變'child.Visibility = System.Windows.Visibility。可見;' – 2012-04-24 22:28:12

+0

看到我的更新 - 你可以設置一個對現有孩子的引用並在之後訪問它。 – McGarnagle 2012-04-24 22:30:53

+0

最後一個疑問是,如果有兩個用戶控件在畫布中,並且一旦我再次單擊以打開該用戶控件,則此代碼將不會打開,但我想將該控件的焦點置於其他控件的頂部 – 2012-04-24 22:44:29

0

或者更簡單地說

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

Linq查詢在Canvas Children上不可能,因爲它沒有實現IEnumerable接口 – 2012-04-25 12:04:39

相關問題