2013-04-27 51 views
1

我試圖創建一個新實例(的Expander),並在每次變量不等於另一個變量時將其放入StackPanel在if語句中創建對象的實例

問題;但是,似乎是我無法訪問if函數外的變量。 我得到:

"Error The name 'expand' does not exist in the current context"

如果我聲明,那麼應用程序的工作原理通過if語句預期運行一次函數之外的新實例。它通過if語句運行第二次,我得到一個錯誤:

"Specified Visual is already a child of another Visual or the root of a CompositionTarget."

if (lastStatement != first.ToString()) { 

    i++; 
    Expander expand = new Expander(); 

    expand.Name = "expander" + i.ToString(); 

    stackpanel1.Children.Add(expand); //This where the error is 
} expand.Content += ones; // I need to place this here for the code to work 

這是我得到的情況:

"Error The name 'expand' does not exist in the current context"

第二次嘗試(當我有外面創建實例聲明)我得到:

"Specified Visual is already a child of another Visual or the root of a CompositionTarget."

回答

1

聲明變量和創建新實例可以在單獨的步驟中完成。您可以簡單地在if區塊之外聲明它並將其實例化,但是,在嘗試使用它之前,仍然需要將其設置爲有效值,否則您將獲得NullReferenceException

事情是這樣的:

Expander expand; 

if (lastStatement != first.ToString()) 
{ 
    i++; 
    expand = new Expander(); 
    expand.Name = "expander" + i.ToString(); 
    stackpanel1.Children.Add(expand); 
} 
else 
{ 
    expand = ... // set expand to some other instance of expander 
} 

expand.Content += ones; 

但是,它看起來像你正在使用某種形式的循環。在這種情況下,您可能會試圖在特定條件下僅創建新的Expander,但在其他情況下重新使用以前的Expander。在這種情況下,你需要在循環塊外聲明變量。

事情是這樣的:

Expander expand = null; 

foreach(...) 
{ 
    if (lastStatement != first.ToString()) 
    { 
     i++; 
     expand = new Expander(); 
     expand.Name = "expander" + i.ToString(); 
     stackpanel1.Children.Add(expand); 
    } 

    expand.Content += ones; 
} 
+0

感謝PSWG,它的工作。我所做的只是聲明擴展器在函數外部爲空,並在本地調用它。 – xterminal0 2013-04-27 04:07:55