你的位置:首页 > ASP.net教程

[ASP.net教程]从一个父级控件找到某一个子级控件

/// <summary>
/// 刷新图层列表,添加素材子元素时间控件TimeRange
/// </summary>
public void RefreshListView()
{
for (int i = 0; i < lstCoverage.Items.Count; i++)      //lstCoverage是一个ListView 控件
{
UIElement u = lstCoverage.ItemContainerGenerator.ContainerFromIndex(i) as UIElement;

if (u == null)
{
Debug.WriteLine("获取的UIElement为空!!……");
continue;
}

clsCoverageInfo tmCvr = lstCoverage.Items[i] as clsCoverageInfo;      //clsCoverageInfo绑定数据源
List<MaterageTiemList> btnList = FindVisualChild<MaterageTiemList>(u);
if(btnList.Count == 0)
{
Debug.WriteLine("查找失败……");
}
else
{
btnList[0].SetView(tmCvr.m_strCoverageMeterals);
Debug.WriteLine("查找成功……");
}

}
}

/// <summary>
/// 利用visualtreehelper寻找对象的子级对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
List<T> FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
try
{
List<T> TList = new List<T> { };
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
{
TList.Add((T)child);
}
else
{
List<T> childOfChildren = FindVisualChild<T>(child);
if (childOfChildren != null)
{
TList.AddRange(childOfChildren);
}
}
}
return TList;
}
catch (Exception ee)
{
// MessageBox.Show(ee.Message);
return null;
}
}