我得到了一个带有contextMenu的简单ListBox:
<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>
我试图从上下文菜单操作的Handler(任何操作)中检索所选ListBoxItem中的“Image”控件。处理程序是:
'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”是Nothing ......
我做错了什么? 感谢
答案 0 :(得分:3)
您将在此行中获取ListBox的内容演示者而不是ListBoxItem:
Dim myContentPresenter As ContentPresenter = FindVisualChild(Of ContentPresenter)(ListBox)