2013-03-26 50 views
1

我有選項卡控件,它有很多選項卡項目,我正在檢查數據網格項目計數,同時關閉選項卡項目。第一次它工作正常(我的意思是在第一次迭代)。關閉一個標籤項後,在第二次迭代中,sellDtg爲空。有誰知道它爲什麼會發生?我擔心這是UI問題,佈局沒有被刷新。請幫助我或顯示方向。Visual Tree Finder在搜索數據網格時返回空值

while (tc.HasItems) 
     { 
      TabItem ti = tc.SelectedItem as TabItem; 
      if (ti.Header == "Продажа") 
      { 
       Microsoft.Windows.Controls.DataGrid sellDtg = FindChild<Microsoft.Windows.Controls.DataGrid>(tc, "SellDataGrid"); 
       if (sellDtg.Items.Count > 0) 
       { 
        Sell sl = new Sell(); 
        if (Sell.basketfromSellDateListBox == false) 
        { 
         sl.ClearBasket(sellDtg); 
         Sell.ClearFromSellBasket((int)sellDtg.Tag); 
        } 
       } 
      } 
      if (ti != null) 
       tc.Items.Remove(ti); 

     } 

在此先感謝!

+0

是TabControl中的DataGrid – 2013-03-26 18:30:37

+0

是的,當然在標籤項 – 2013-03-26 18:31:29

回答

1

我寫類似於一個簡單FindChildLogical功能如下LogicalTreeHelper

public static T FindChildLogical<T>(DependencyObject parent, string childName) 
      where T : DependencyObject 
     { 
      if (parent == null) return null; 
      var child = LogicalTreeHelper.FindLogicalNode(parent, childName); 

      return (T)child; 
     } 

,你叫它爲:

Microsoft.Windows.Controls.DataGrid sellDtg = FindChildLogical<Microsoft.Windows.Controls.DataGrid>(ti, "SellDataGrid"); 

我希望它可以讓你,你打算。

+0

完美,適合我的作品!!!!!謝謝你,先生!!! – 2013-03-27 14:11:58

0

我打算假設你的FindChild方法使用VisualTreeHelper來找到它的孩子。

在第一次迭代中,TabItemContent已通過佈局傳遞,並且可見。這意味着TabItemContent將在視覺樹中。

但是,對於其他選項卡項目,它們的Content尚未經過佈局階段(只有在父項被選中時才添加到可視化樹中,然後必須通過佈局/渲染階段) ,並且不會在視覺樹中。

有一對夫婦的方式獲得TabItem未經過佈局傳遞作爲選定選項卡中的子內容:

1)你可以嘗試使用LogicalTreeHelper找到Grid你」重新尋找(並且您可能必須搜索TabItemContent,而不是TabControl)。

2)你可以把你的代碼了while循環,並在加載優先做調度的回調:

void RemoveAllItems() 
{ 
    if (!tc.HasItems) return; 

    TabItem ti = tc.SelectedItem as TabItem; 
    if (ti.Header == "Продажа") 
    { 
     var sellDtg = FindChild<Microsoft.Windows.Controls.DataGrid>(tc, "SellDataGrid"); 
     if (sellDtg.Items.Count > 0) 
     { 
      Sell sl = new Sell(); 
      if (Sell.basketfromSellDateListBox == false) 
      { 
       sl.ClearBasket(sellDtg); 
       Sell.ClearFromSellBasket((int)sellDtg.Tag); 
      } 

      if (ti != null) 
       tc.Items.Remove(ti); 
     } 
    } 

    Dispatcher.BeginInvoke(new Action(RemoveAllItems), DispatcherPriority.Loaded); 
} 

如果使用第二種方法,你可能能夠看到一次只移除一個標籤項目,這可能是您不想看到的內容。

+0

內我無法弄清楚如何在我的代碼中實現它。請幫助我 – 2013-03-27 10:44:33

+0

我添加了您的原始代碼以使答案更清晰。 – 2013-03-27 13:02:07

+0

代碼正在工作,但這不是我想要的。讓我解釋一下我在做什麼,我有選項卡項目讓我們說出售選項卡項目。在每個出售選項卡項目我檢查DataGrid項目計數,如果它是> 0我正在返回到股票。在你的代碼中它只返回最後一個(出售標籤項目),但之前的標籤項目(它可能有多個銷售標籤項目)正在丟失(不返回到我的股票 – 2013-03-27 13:19:45