问题描述
我在 itemscontrol 的数据模板中只有几个文本框.当我将 itemcontrols 绑定到一个 observable 集合时,我得到两个文本框.但是我需要根据每个文本框进行一些操作,我想使用一些 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 中的 itemscontrol 中找到控件.
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);
这篇关于在 WPF itemscontrol 中查找控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!