做项目时找到的要领,引用自,感受挺好的,生存下来
获取在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下的子控件
,