我创建的ListBox
DataTemplate
为Itemtemplate
。但是,有一种简单的方法可以在代码隐藏中访问生成的UIElement
而不是SelectedItem
吗?
当我访问SelectedItem
时,我只是从我的中获取所选对象
ItemsSource
集合。有没有办法访问UIElement
(即
从DataTemplate
和绑定对象一起生成的元素??
答案 0 :(得分:13)
您正在寻找ItemContainerGenerator财产。每个ItemsSource
都有ItemContainerGenerator个实例。此类具有您可能感兴趣的以下方法:ContainerFromItem(object instance)。
获得ListBoxItem
的句柄后,您可以继续浏览逻辑树和可视树。查看Logical Tree Helper和Visual Tree Helper。
就像Andy在评论中所说的那样,仅仅因为你的收藏中存在该项目并不意味着已经为它生成了一个容器。任何类型的虚拟化面板场景都会引发这个问题; UIElements将在不同的项目中重复使用。也要小心。
答案 1 :(得分:4)
siz , Andy 和 Bodeaker 绝对正确。
以下是我如何使用句柄检索列表框所选项目的文本框。
var container = listboxSaveList.ItemContainerGenerator.ContainerFromItem(listboxSaveList.SelectedItem) as FrameworkElement;
if (container != null)
{
ContentPresenter queueListBoxItemCP = VisualTreeWalker.FindVisualChild<ContentPresenter>(container);
if (queueListBoxItemCP == null)
return;
DataTemplate dataTemplate = queueListBoxItemCP.ContentTemplate;
TextBox tbxTitle = (TextBox)dataTemplate.FindName("tbxTitle", queueListBoxItemCP);
tbxTitle.Focus();
}
(注意:这里,VisualTreeWalker是我自己的VisualTreeHelper包装器,暴露了各种有用的功能)