WPF:为ListViewItem添加ContextMenu

时间:2018-03-21 13:21:47

标签: wpf listview contextmenu listviewitem

所以这是我的ListView

<ListView Name="lvFiles"
          ItemContainerStyle="{StaticResource ListViewItemDefaultStyle}"/>

样式(此style位于另一个文件中:ListViewItem.xaml):

<Style x:Key="ListViewItemDefaultStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="Foreground" Value="Gainsboro"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <!--<Setter Property="FontFamily" Value="Calibri"/>-->
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                    <Border
                        BorderBrush="{TemplateBinding BorderBrush}" 
                        BorderThickness="{TemplateBinding BorderThickness}" 
                        Background="{TemplateBinding Background}" 
                        CornerRadius="2" SnapsToDevicePixels="true">
                        <Border
                            x:Name="InnerBorder"
                            BorderThickness="1"
                            CornerRadius="1">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition MaxHeight="11"/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <GridViewRowPresenter
                                    Grid.RowSpan="2"
                                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Grid>
                        </Border>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>

        </Style.Triggers>
    </Style>

现在我要添加此ContexMenu

  <ContextMenu>
        <MenuItem Name="menuItemClose"
                  Header="Exit"
                  Click="menuItemClose_Click"/>
        <MenuItem Name="menuItemOpen"
                  Header="Open"
                  Click="menuItemOpen_Click"/>
    </ContextMenu>

首先我需要定义这个ContextMenu

以及如何将其添加到我的ListView&gt;

1 个答案:

答案 0 :(得分:0)

只需在您的样式中添加另一个setter即可设置ContextMenu属性:

 <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <MenuItem Name="menuItemClose"
                              Header="Exit"
                              Click="menuItemClose_Click"/>
                    <MenuItem Name="menuItemOpen"
                              Header="Open"
                              Click="menuItemOpen_Click"/>
                </ContextMenu>
            </Setter.Value>
        </Setter>