右键单击ListBox项时如何显示按钮或标签

时间:2014-01-03 22:13:51

标签: c# wpf mvvm

我是WPF和MVVM的新手,我已经构建了一些东西,现在尝试在用户右键单击ListBox项时显示删除“按钮”。 我的列表框现在看起来像这样

 <ListBox DisplayMemberPath="QUERYNAME" 
                 SelectedValuePath="USERQUERYID" 
                 ItemsSource="{Binding RS.SavedQueryList, UpdateSourceTrigger=PropertyChanged}"
                 SelectedValue="{Binding RS.SelectedValue, UpdateSourceTrigger=PropertyChanged}"
                 Height="300" HorizontalAlignment="Left" Name="listBox2" VerticalAlignment="Top" Width="101" Margin="521,74,0,0" TabIndex="0">            

由于

3 个答案:

答案 0 :(得分:1)

您可以将按钮和标签(实际上是您想要的任何元素)添加到ContextMenu,并将ContextMenu分配给ListBoxItem。例如,在我的Window中,我会有类似的内容:

  <Window.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                        <TextBlock Text="Delete This Item" Margin="10"/>
                        <Button Content="Delete"/>
                    </StackPanel>
                </ContextMenu>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

这将使用Styles的强大功能将自定义ContextMenu应用于窗口的所有ListBoxItem。之后,您可以将Button.Command绑定到ViewModel。

答案 1 :(得分:0)

你可以通过使用MVVM灯光行为 EventToCommand 来看看http://msdn.microsoft.com/en-us/magazine/dn237302.aspx

将事件设置为 MouseRightButtonUp

答案 2 :(得分:0)

<ListBox DisplayMemberPath="QUERYNAME" 
                 SelectedValuePath="USERQUERYID" 
                 ItemsSource="{Binding RS.SavedQueryList, UpdateSourceTrigger=PropertyChanged}"
                 SelectedValue="{Binding RS.SelectedValue, UpdateSourceTrigger=PropertyChanged}"
                 Height="300" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="101" Margin="521,74,0,0" TabIndex="0">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete">
                <MenuItem.Icon>
                    <Image Width="16" Height="16" Source="pack://application:,,,/Img/Delete.png" />
                 </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    <ListBox.ContextMenu>      
</ListBox>

显然你需要在你的MenuItem中使用一些Command ......

相关问题