2013-02-05 79 views
1

我得到這個簡單的列表框與文本菜單:WPF列表框ContentPresenter.ContentTemplate什麼

<ListBox BorderThickness="1" BorderBrush="Gray" SelectionChanged="TableList_SelectionChanged" Grid.Column="0" x:Name="TableList"> 

      <ListBox.ContextMenu> 
       <ContextMenu> 
        <MenuItem Click="MenuItem_Click" Header="Ajouter"/> 
        <MenuItem Click="MenuItem_Click_1" Header="Supprimer"/> 
       </ContextMenu> 
      </ListBox.ContextMenu> 

      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <Image Name="Image" Height="12px" Width="12px" Source="Apply.gif"> 
          <Image.Margin> 
           <Thickness Right="10"></Thickness> 
          </Image.Margin> 
         </Image> 
         <TextBlock Text="{Binding Path=Content}" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 

     </ListBox> 

,我試圖找回「圖像」控制從上下文菜單操作的處理程序(選擇一個ListBoxItem任何行動)。因此,處理程序是:

'Dim ListBox As ListBox = DirectCast(sender.Parent, System.Windows.Controls.ContextMenu).PlacementTarget 
    Dim ListBox As ListBox = Me.TableList 
    Dim myListBoxItem As ListBoxItem = CType(ListBox.ItemContainerGenerator.ContainerFromItem(ListBox.Items.CurrentItem), ListBoxItem) 

    ' Getting the ContentPresenter of myListBoxItem 
    Dim myContentPresenter As ContentPresenter = FindVisualChild(Of ContentPresenter)(ListBox) 

    ' Finding textBlock from the DataTemplate that is set on that ContentPresenter 
    Dim myDataTemplate As DataTemplate = myContentPresenter.ContentTemplate 

根據這一link形式的MSDN,我可以打電話從DataTemplate中的「findName」的方法。但是變量「myDataTemplate」是沒什麼......

我在做什麼錯? 感謝

回答

3

你得到列表框,而不是一個ListBoxItem的內容展示在這一行:

昏暗myContentPresenter作爲ContentPresenter = FindVisualChild(中ContentPresenter)(列表框)

+0

當然,....什麼錯誤。謝謝 – Neb

+0

歡迎:) –