簡體   English   中英

如何從上下文菜單中獲取所選項目

[英]How to get the selected item from a context menu

我有一個綁定到項目列表的上下文菜單。 當我單擊一個項目時,該命令會執行,但是我在將所選項目作為參數傳遞時遇到了問題,誰能確定我做錯了什么?

我曾嘗試將{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}作為命令參數傳遞{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}但是它只是給了我上下文菜單中的整個列表和時間。 當我嘗試{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}沒有看到任何值。

    <ContextMenu x:Key="SelectFileTab" ItemsSource="{Binding ContextMenuItems}" x:Name="contextmenu">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <MenuItem Header="{Binding}">
                </MenuItem>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewMouseUp">
                <i:InvokeCommandAction Command="{Binding SelectedFileToAdd, Mode=OneWay}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>

    </ContextMenu>     

我真的把一些很簡單的事情復雜化了,沒有必要在命令中使用interaction.triggers 問題,我需要做的就是

<ContextMenu x:Key="SelectFileTab" ItemsSource="{Binding ContextMenuItems}" x:Name="contextmenu">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                 <MenuItem Header="{Binding}" Command="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.SelectedFileToAdd}"
                                       CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
   </ContextMenu>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM