WPF ListBox - 获取 UIElement 而非 SelectedItem

14

我创建了一个带有 DataTemplate 作为 ItemtemplateListBox。然而,在代码中有没有一种简单的方法来访问生成的 UIElement,而不是SelectedItem

当我访问 SelectedItem 时,我只能得到从我的ItemsSource集合中选择的对象。是否有一种方法可以访问UIElement(即从DataTemplate生成的元素与绑定的对象一起)?

2个回答

14
你正在寻找ItemContainerGenerator属性。每个ItemsSource都有一个ItemContainerGenerator实例。这个类有以下可能会对你有用的方法:ContainerFromItem(object instance)
一旦你拥有了ListBoxItem的句柄,你就可以浏览逻辑树和视觉树。查看Logical Tree HelperVisual Tree Helper
正如Andy在评论中所说的那样,仅仅因为该项存在于你的集合中并不意味着已经为它生成了一个容器。任何虚拟面板方案都会引发这个问题;UIElements将在不同的项之间被重用。也要注意这一点。

请注意,仅仅因为一个项目已经添加到控件中,并不意味着它的UI容器已经生成。确保考虑还没有UI容器的情况。 - Andy
我正在使用C#和WPF编写代码,但是在ListBox.ItemsContainer下找不到该属性。我该如何获取此列表框的实例? - sprite
@size,你有我的问题的解决方案吗?https://dev59.com/3FfUa4cB1Zd3GeqPJqHt(+250赏金) - tofutim
6
仅供参考,以下是我已经成功运行的完整代码: var container = ListBox.ItemContainerGenerator.ContainerFromItem(ListBox.SelectedItem) as FrameworkElement; if (container != null) container.Focus(); - Bodekaer

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();
}

(注意:这里,VisualTreeWalker是我自己封装的VisualTreeHelper,提供了许多有用的函数)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接