在WPF项目中找到控件
我在itemsTemplate的datatemplate内只有几个文本框.当我将itemcontrols绑定到一个可观察的集合时,我得到两个文本框.但是我需要根据每个文本框进行一些操作,为此我想使用一些ID分别找到每个文本框.
Hi i have few a single textbox within the the datatemplate for itemscontrol. When i bind the itemcontrols to a observable collection i get two text boxes. But i need to do some manipulations based on each of the text boxes for which i want to find each textbox seperatly using some id.
任何人都可以在WPF中的项目控件中找到如何找到控件的帮助吗.
Can anybody help on how to find a control witin the itemscontrol in WPF.
使用ItemContainerGenerator,您可以获得项目的生成容器,并向下遍历可视树以找到您的TextBox.对于ItemsControl,它将是ContentPresenter,但是ListBox将返回ListBoxItem,ListView,ListViewItem等.
Using the ItemContainerGenerator you can obtain the generated container for an item and traverse the visual tree downwards to find your TextBox. In the case of an ItemsControl it will be a ContentPresenter, but a ListBox will return a ListBoxItem, ListView a ListViewItem, etc.
ContentPresenter cp = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as ContentPresenter;
TextBox tb = FindVisualChild<TextBox>(cp);
if (tb != null)
{
// do something with tb
}
public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
如果需要,还可以通过使用索引获取容器
You can also obtain the container by index if you want by using
itemsControl.ItemContainerGenerator.ContainerFromIndex(0);