我得到了这个带有 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>
我正在尝试从上下文菜单操作(任何操作)的处理程序中检索所选 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
根据这个链接表单 MSDN,我可以从 DataTemplate 调用“findName”方法。但是变量“myDataTemplate”什么都没有……
我究竟做错了什么?谢谢