2009-03-04 17 views
10

我創建了一個ListBox,它的DataTemplateItemtemplate。但是,有沒有簡單的方法來訪問生成的UIElement而不是代碼隱藏中的SelectedItemWPF列表框 - 獲取UIElement而不是SelectedItem

當我訪問SelectedItem時,我只是從我的 ItemsSource集合中獲取所選對象。有沒有辦法訪問UIElement(即DataTemplate與綁定對象一起生成的 元素)?

回答

11

您正在尋找ItemContainerGenerator住宅。每個ItemsSource都有一個ItemContainerGenerator實例。本課有以下方法可能會讓你感興趣:ContainerFromItem(object instance)

一旦您掌握了ListBoxItem,就可以繼續瀏覽邏輯樹和可視化樹。檢出Logical Tree HelperVisual Tree Helper

就像Andy在評論中所說的,只是因爲該物品存在於你的收藏中並不意味着它已經生成了一個容器。任何種類的虛擬化小組都會引發這個問題; UIElements將在不同的項目中重複使用。還要小心。

+0

注意,僅僅因爲一個項目已被添加到所控制,這並不意味着它的UI容器已經生成。確保說明尚未有UI容器的情況。 – Andy 2009-03-04 17:34:21

4

SIZ安迪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與暴露的各種有用的功能)

相關問題