1

我得到了这个带有 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”什么都没有……

我究竟做错了什么?谢谢

4

1 回答 1

3

在这一行中,您将获得 ListBox 而不是 ListBoxItem 的内容演示者:

将 myContentPresenter 调暗为 ContentPresenter = FindVisualChild(Of ContentPresenter)(ListBox)

于 2013-02-05T15:08:03.690 回答