14

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

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

4

2 回答 2

14

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

一旦您掌握了ListBoxItem,您就可以继续浏览逻辑和可视化树。查看Logical Tree HelperVisual Tree Helper

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

于 2009-03-04T17:26:20.720 回答
5

大小安迪博德克是绝对正确的。

以下是我如何能够使用其句柄检索列表框的选定项目的文本框。

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

于 2013-08-02T03:57:37.120 回答