I got this simple ListBox with a contextMenu:
<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>
and I am trying to retrieve the “Image” control in the selected ListBoxItem from the Handler of the context menu action (any action). So the handler is:
'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
According to this link form MSDN, I could call the “findName” method from the DataTemplate. But The variable “myDataTemplate” is Nothing…
What am I doing wrong?
Thanks
You’re getting content presenter of ListBox instead of ListBoxItem in this line:
Dim myContentPresenter As ContentPresenter = FindVisualChild(Of ContentPresenter)(ListBox)