context menu for removing items in listview

后端 未结 3 910
轮回少年
轮回少年 2021-02-02 17:23

I have a ListView which displays a list of string values. I want to add a context menu entry for each item in the list to remove the selected item. My XAML looks like this:

相关标签:
3条回答
  • 2021-02-02 17:59

    ContextMenus are disconnected, you cannot use ElementName bindings. One workaround would be using Binding.Source and x:Reference which requires you to extract parts that use it to be in the resources (due to cyclical dependency errors). You can just put the whole context menu there.

    An example:

    <ListBox Name="lb" Height="200">
        <ListBox.Resources>
            <ContextMenu x:Key="cm">
                <MenuItem Header="{Binding ActualHeight, Source={x:Reference lb}}" />
            </ContextMenu>
        </ListBox.Resources>
        <ListBox.ContextMenu>
            <StaticResource ResourceKey="cm" />
        </ListBox.ContextMenu>
    </ListBox>
    
    0 讨论(0)
  • 2021-02-02 18:03

    This work for me CommandParameter="{Binding}"

    0 讨论(0)
  • 2021-02-02 18:09

    H.B. is right. but you can also use RelativeSource Binding

        <ListView x:Name="itemsListView" ItemsSource="{Binding MyItems}">
            <ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Remove"
                Command="{Binding RemoveItem}"
                CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
                </ContextMenu>
            </ListView.ContextMenu>
        </ListView>
    
    0 讨论(0)
提交回复
热议问题