WPF ListBox-获取UIElement而不是SelectedItem [英] WPF ListBox - Getting UIElement instead of of SelectedItem
问题描述
我创建了一个ListBox
,其DataTemplate
作为Itemtemplate
.但是,有没有一种简单的方法可以访问生成的UIElement
而不是代码背后的SelectedItem
?
I created a ListBox
that has a DataTemplate
as Itemtemplate
. However, is there an easy way to access the generated UIElement
instead of the SelectedItem
in codebehind?
当我访问SelectedItem
时,我只是从我的计算机中获取了选定的对象
ItemsSource
集合.有没有一种方法可以访问UIElement
(即
DataTemplate
与绑定对象一起生成的元素)?
When I access SelectedItem
, I just get the selected object from my
ItemsSource
collection. Is there a way to access the UIElement
(ie. the
element generated from the DataTemplate
together with the bound object)?
推荐答案
您正在寻找 ItemContainerGenerator 实例.此类具有以下您可能感兴趣的方法: ContainerFromItem(对象实例).
You are looking for the ItemContainerGenerator property. Each ItemsSource
has an ItemContainerGenerator instance. This class has the following method that might interest you: ContainerFromItem(object instance).
一旦您拥有ListBoxItem
的手柄,就可以继续浏览逻辑和可视化树.查看逻辑树帮助器和视觉树助手.
Once you have a handle to the ListBoxItem
, you can go ahead and browse the logical and visual tree. Check out Logical Tree Helper and Visual Tree Helper.
就像安迪(Andy)在评论中说的那样,仅仅因为该项目存在于您的收藏夹中并不意味着已经为其生成了一个容器.任何一种虚拟化面板方案都会引发此问题. UIElement将在不同的项目之间重用.还要小心.
Like Andy said in the comments, just because the item exists in your collection doesn't mean a container has been generated for it. Any kind of virtualizing panel scenario will raise this issue; UIElements will be reused across the different items. Be careful with that as well.
这篇关于WPF ListBox-获取UIElement而不是SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!