我创建了一个 ListBox ,其 DataTemplate Itemtemplate 。但是,是否有一种简单的方法可以在代码隐藏中访问生成的 UIElement 而不是 SelectedItem

当我访问 SelectedItem 时,我只是从我的中获取所选对象 ItemsSource 集合。有没有办法访问 UIElement (即 从 DataTemplate 和绑定对象一起生成的元素??

有帮助吗?

解决方案

您正在寻找 ItemContainerGenerator 财产。每个 ItemsSource 都有一个 ItemContainerGenerator 实例。此类具有您可能感兴趣的以下方法: ContainerFromItem(对象实例)

获得 ListBoxItem 的句柄后,您可以继续浏览逻辑树和可视树。查看 Logical Tree Helper Visual Tree Helper

就像Andy在评论中所说的那样,仅仅因为你的收藏中存在该项目并不意味着已经为它生成了一个容器。任何类型的虚拟化面板场景都会引发这个问题; UIElements将在不同的项目中重复使用。也要小心。

其他提示

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包装器,暴露了各种有用的功能)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top