ListBox contextMenu SubItem点击

时间:2018-01-16 12:05:36

标签: c# wpf windows xaml listbox

ListBox ContextMenu,我已配置MenuItem仅在我点击所选项目时才有效。

这是XAML代码:

<ListBox x:Name="MessagesLb" Grid.Column="1" Margin="241,100,22.4,50" Grid.Row="1" BorderThickness="0" FontSize="14" FontWeight="SemiBold" ItemsSource="{Binding Items}" SelectionMode="Extended">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu>
                                <MenuItem Header="Copia" Click="MessagesLbCopySubMi_Click" />
                                <Separator/>
                                <MenuItem Header="Dettagli" />
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" Value="0">
                            <Setter Property="ContextMenu" Value="{x:Null}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我尝试在Click中添加MenuItem个事件,但它不起作用。

示例:

<MenuItem Header="Copia" Click="MessagesLbCopySubMi_Click" />

private void MessagesLbCopySubMi_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Click event done");
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

ContextMenu定义为资源:

<ListBox x:Name="MessagesLb" Grid.Column="1" Margin="241,100,22.4,50" Grid.Row="1" BorderThickness="0" FontSize="14" FontWeight="SemiBold" 
         ItemsSource="{Binding Items}" SelectionMode="Extended">
    <ListBox.Resources>
        <ContextMenu x:Key="cm">
            <MenuItem Header="Copia" Click="MessagesLbCopySubMi_Click" />
            <Separator/>
            <MenuItem Header="Dettagli" />
        </ContextMenu>
    </ListBox.Resources>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContextMenu" Value="{StaticResource cm}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" Value="0">
                    <Setter Property="ContextMenu" Value="{x:Null}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>