WPF 查找ListBox等DataTemplate下的子控件
做項目時找到的方法,引用自http://bbs.csdn.net/topics/390890082,覺得挺好的,保存下來
獲取在ListBox中的DataTemplate下的每一個button對象的方法如下:
private T SearchVisualTree<T>(DependencyObject tarElem) where T : DependencyObject
{
if (tarElem != null)
{
var count = VisualTreeHelper.GetChildrenCount(tarElem);
if (count == 0)
return null;
for (int i = 0; i < count; ++i)
{
var child = VisualTreeHelper.GetChild(tarElem, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
var res = SearchVisualTree<T>(child);
if (res != null)
{
return res;
}
}
}
return null;
}
private void GetBtn()
{
for (int i = 0; i < this.ListBoxName.Items.Count; i++)
{
ListBoxItem itemtemp = this.ListBoxName.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
Button buttonobject = SearchVisualTree<Button>(itemtemp);
if (buttonobject == null) break;
buttonobject.Margin = new Thickness(10, 10, 10, 10);
}
}
WPF 查找ListBox等DataTemplate下的子控件