简体   繁体   English

WPF中ListBox的上下文菜单项

[英]Context Menu Item for ListBox in WPF

I want to display ContextMenu on right click of ListBoxItems in WPF. 我想在WPF中的ListBoxItems的右键单击上显示ContextMenu。 I tried below code, but ContextMenu is displaying where ListBoxItems are not there also. 我尝试了下面的代码,但是ContextMenu显示的是ListBoxItems也不存在的地方。 What I want is to display ContextMenu only on the right click of only ListBoxItems. 我想要的是仅在ListBoxItems的右键单击上显示ContextMenu。

<Grid>
<ListBox x:Name="listofConnectedItems" Grid.Column="0" Grid.Row="0" ItemsSource="{Binding MyItems}" MouseRightButtonDown="listofConnectedItems_MouseRightButtonDown" ContextMenuOpening="listofConnectedItems_ContextMenuOpening" >
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Padding" Value="10">

                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ContextMenu>
            <ContextMenu>
                <MenuItem Header="_Start" Click="MenuItemStart_Click"  />
                <MenuItem Header="Sto_p" Click="MenuItemStop_Click" />
                <MenuItem Header="_Clear" Click="MenuItemClear_Click" />
            </ContextMenu>
        </ListBox.ContextMenu>

    </ListBox>
</Grid>

` Here I attached the screenshot. `在这里,我附上了屏幕截图。 在此处输入图片说明 Can anybody Please get me through this. 谁能帮我解决这个问题。 Thanks in advance 提前致谢

It should be in IntemContainerStyle : 它应该是IntemContainerStyle

<ListBox.ItemContainerStyle>
   <Style TargetType="ListBoxItem">
       <Setter Property="ContextMenu">
           <Setter.Value>
               <ContextMenu>
                   <MenuItem Header="Open" />
                   <MenuItem Header="Edit" Command="Binding 
               </ContextMenu>
           </Setter.Value>
       </Setter>
   </Style>
</ListBox.ItemContainerStyle>

I think the problem is that You didn't specified height and width of list box so it automaticaly scales to the window size. 我认为问题是您没有指定列表框的高度和宽度,因此它会自动缩放到窗口大小。 So technically Your code is working correctly but listbox is everywhere. 因此,从技术上讲,您的代码可以正常工作,但列表框无处不在。

try with something like 尝试像

<ListBox x:Name="listofConnectedItems" Grid.Column="0" Grid.Row="0" BorderThickness="5" Width="200" Height="200"...

and then rightclick outside the listbox 然后在列表框外单击鼠标右键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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