简体   繁体   中英

WPF lists and context menus

Which WPF control allows listing of items and context menus on each of the items? Up until now, I've been using a ListBox, but it seems as though there's no easy way of adding context menus to its items. Instead, I'm looking at changing the ListBox to another control that does allow context menus.

The only ListBox properties/methods I'm using right now are "SelectedIndex" and "SelectedItem". As long as the suggested control supports this or has another substitute, I should be fine.

To add a ContextMenu to ListBoxItem you use the ItemContainerStyle

<ListBox ItemsSource="{Binding ...}">
    <ListBox.Resources>
        <ContextMenu x:Key="listBoxItemContextMenu">
            <MenuItem Header="{Binding YourProperty}" />
        </ContextMenu>
    </ListBox.Resources>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContextMenu"
                    Value="{StaticResource listBoxItemContextMenu}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <!--...-->
</ListBox>

You can use the DataGrid control in wpf for listing. Also you can add contextMenu like

<DataGrid AutoGenerateColumns="False" Height="200"  Width="200" >
        <DataGrid.ContextMenu>
        <ContextMenu >
            <MenuItem Header="Menu Header" Click="MenuItem_Click"  />
        </ContextMenu>
        </DataGrid.ContextMenu>
</DataGrid>

Also refer Create contextmenus for datagrid rows

This example doesn't use any binding or DataTemplates like you might typically see in a real app, but hopefully it helps

    <ListBox>
        <ListBox.Items>
            <ListBoxItem Content="Item A">
                <ListBoxItem.ContextMenu>
                    <ContextMenu>Delete A</ContextMenu>
                </ListBoxItem.ContextMenu>
            </ListBoxItem>
            <ListBoxItem Content="Item B">
                <ListBoxItem.ContextMenu>
                    <ContextMenu>Delete B</ContextMenu>
                </ListBoxItem.ContextMenu>
            </ListBoxItem>
            <ListBoxItem Content="Item C">
                <ListBoxItem.ContextMenu>
                    <ContextMenu>Delete A</ContextMenu>
                </ListBoxItem.ContextMenu>
            </ListBoxItem>
        </ListBox.Items>
    </ListBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM