我有一個tabcontrol中有9個tabitems的tabcontrol。每個選項卡都有一系列文本框供用戶輸入數據。在底部是一個清除按鈕,迷上了這種方法:遍歷TabControl中的TabItems
public void ClearTextBoxes()
{
ChildControls ccChildren = new ChildControls();
foreach (object o in ccChildren.GetChildren(rvraDockPanel, 2))
{
if (o.GetType() == typeof(WatermarkTextBox) || o.GetType() == typeof(DateBox) ||
o.GetType() == typeof(DigitBox) || o.GetType() == typeof(PhoneBox))
{
WatermarkTextBox water = (WatermarkTextBox)o;
water.Text = "";
}
else if (o.GetType() == typeof(ComboBox))
{
ComboBox combo = (ComboBox)o;
combo.SelectedIndex = -1;
}
else if (o.GetType() == typeof(CheckBox))
{
CheckBox check = (CheckBox)o;
check.IsChecked = false;
}
}
}
這工作完全正常,但我也有一個菜單項,允許用戶ClearAll標籤。現在,清除按鈕只會清除當前選中的選項卡上的內容,並保留其他所有內容。我如何做到這一點的想法是通過這個循環中的TabItems迭代:
for (int i = 0; i < 10; i++)
{
tabSelection.SelectedIndex = i;
clearButton_Click(null, null);
}
它會翻閱所有選項卡,但不會明確的東西。我試過使用自動化代替,結果相同。它似乎並不清楚任何事情。
ChildControls類:
class ChildControls
{
private List<object> listChildren;
public List<object> GetChildren(Visual p_vParent, int p_nLevel)
{
if (p_vParent == null)
{
throw new ArgumentNullException("Element {0} is null!", p_vParent.ToString());
}
this.listChildren = new List<object>();
this.GetChildControls(p_vParent, p_nLevel);
return this.listChildren;
}
private void GetChildControls(Visual p_vParent, int p_nLevel)
{
int nChildCount = VisualTreeHelper.GetChildrenCount(p_vParent);
for (int i = 0; i <= nChildCount - 1; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(p_vParent, i);
listChildren.Add((object)v);
if (VisualTreeHelper.GetChildrenCount(v) > 0)
{
GetChildControls(v, p_nLevel + 1);
}
}
}
}
我認爲這與WPF行爲與TabControl有關。我已經讀過,當一個標籤離開視圖時,前一個標籤的可視化樹會被「丟棄」。您可能想要將Clear()抽象爲一個類。 – 2011-12-14 16:04:12