我创建了ListBox
一个DataTemplate
as Itemtemplate
。但是,有没有一种简单的方法可以访问生成的代码UIElement
而不是SelectedItem
代码隐藏?
当我访问时SelectedItem
,我只是从我的
ItemsSource
集合中获取选定的对象。有没有办法访问UIElement
(即DataTemplate
与绑定对象一起生成的元素)?
我创建了ListBox
一个DataTemplate
as Itemtemplate
。但是,有没有一种简单的方法可以访问生成的代码UIElement
而不是SelectedItem
代码隐藏?
当我访问时SelectedItem
,我只是从我的
ItemsSource
集合中获取选定的对象。有没有办法访问UIElement
(即DataTemplate
与绑定对象一起生成的元素)?
您正在寻找ItemContainerGenerator属性。每个ItemsSource
都有一个ItemContainerGenerator实例。此类具有您可能感兴趣的以下方法:ContainerFromItem(object instance)。
一旦您掌握了ListBoxItem
,您就可以继续浏览逻辑和可视化树。查看Logical Tree Helper和Visual Tree Helper。
就像安迪在评论中所说的那样,仅仅因为该项目存在于您的收藏中并不意味着已经为它生成了一个容器。任何类型的虚拟化面板场景都会引发这个问题;UIElements 将在不同的项目中重复使用。也要小心。
大小,安迪和博德克是绝对正确的。
以下是我如何能够使用其句柄检索列表框的选定项目的文本框。
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 的包装器,其中暴露了各种有用的功能)