WPF ListBox - 获取UIElement而不是SelectedItem

Joa*_*mer 13 wpf listbox selecteditem datatemplate uielement

我创建了一个ListBoxDataTemplateas的Itemtemplate.但是,是否有一种简单的方法来访问生成UIElement而不是代码SelectedItem隐藏?

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

Szy*_*zga 14

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

一旦有了句柄ListBoxItem,就可以继续浏览逻辑和可视树.查看Logical Tree HelperVisual Tree Helper.

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

  • 仅供参考,这是我工作的完整代码:`var container = ListBox.ItemContainerGenerator.ContainerFromItem(ListBox.SelectedItem)as FrameworkElement; if(container!= null)container.Focus();` (6认同)

vam*_*afa 5

sizAndyBodeaker是绝对正确的。

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

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();
}
Run Code Online (Sandbox Code Playgroud)

(注意:这里,VisualTreeWalker 是我自己对 VisualTreeHelper 的包装器,公开了各种有用的功能)