WPF ListBox - 获取 UIElement 而不是 SelectedItem [英] WPF ListBox - Getting UIElement instead of of SelectedItem

查看:20
本文介绍了WPF ListBox - 获取 UIElement 而不是 SelectedItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 ListBox,其中有一个 DataTemplate 作为 Itemtemplate.但是,有没有一种简单的方法可以访问生成的 UIElement 而不是 codebehind 中的 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 属性.每个 ItemsSource 都有一个 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 在评论中所说的那样,仅仅因为该项目存在于您的收藏中并不意味着已经为它生成了一个容器.任何类型的虚拟化面板场景都会引发这个问题;UIElements 将在不同的项目中重复使用.也要小心.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆