摘要:WP7-ListBoxExtension
寫習慣ASP.NET與Window Form遇到有子階層控制項的物件都很反射性的下FindControl
但是之前寫Window Phone 7有用到ListBox卻發現沒這個方法,而要用VisualTreeHelper去取得樹狀結構在進行一些處理
而我這個人又很懶...重複的code不想寫太多次...所以就寫了這個擴充方法
namespace Yos.Dev.Ext
{
public static class ListBoxExtension
{
public static T FindControl(this ListBox listBox, int rowIndex, string childName) where T : FrameworkElement
{
DependencyObject listItem = listBox.ItemContainerGenerator.ContainerFromIndex(rowIndex);
return listItem.FindControl(childName);
}
public static T FindControl(this DependencyObject item, string childName) where T : FrameworkElement
{
int count = VisualTreeHelper.GetChildrenCount(item);
for (int index = 0; index < count; index++)
{
DependencyObject citem = VisualTreeHelper.GetChild(item, index);
if (citem is T && ((T)citem).Name == childName)
return ((T)citem);
T t = citem.FindControl(childName);
if (t != null && t.Name == childName)
return t;
}
return null;
}
}
}