Right-click on a Listbox in a Silverlight 4 app

岁酱吖の 提交于 2019-12-01 00:16:29

I've been looking around for the same thing. I checked the Silverlight Control Toolkit at CodePlex and went through the samples (it's a very handy resource) and here's what I found to be the solution to what you asked:

  1. Create an ItemTemplate for your ListBox

  2. in the part that you want to be "right-clickable" of your ItemTemplate set the attached property ContextMenuService.ContextMenu that exists within the System.Windows.Controls.Input.Toolkit namespace

  3. add MenuItem controls to your ContextMenu and set the Click property to the corresponding click event handler

  4. in the event handler, get the DataContext from the sender (you can use that to find the corresponding element in the ListBox)

  5. to make that element Selected, just set the SelectedItem property in the list box to it

  6. Add any custom logic to the event handler

There's an example in the samples page, just go to "Input->ContextMenu" from the navigation pane.

If you want something concise, Here's a simplified example:

<ListBox ItemsSource="{StaticResource People}"
             Name="myListBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}">
                    <controlsInputToolkit:ContextMenuService.ContextMenu>
                        <controlsInputToolkit:ContextMenu>
                            <controlsInputToolkit:MenuItem Header="Show in MessageBox"
                                                           Click="show_Click" />
                        </controlsInputToolkit:ContextMenu>
                    </controlsInputToolkit:ContextMenuService.ContextMenu>
                </TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

with:

xmlns:controlsInputToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"

for the code:

private void show_Click(object sender, RoutedEventArgs e)
    {
        var person = ((MenuItem)sender).DataContext as Person;
        if (null == person) return;
        MessageBox.Show("My Name is: " + person.Name);
        myListBox.SelectedItem = person;
    }

I hope this helps :)

There's the MouseRightButtonDown event. If you bind that on the ListBox:

<ListBox Height="143" Name="listBox1" Width="218"
         MouseRightButtonDown="listBox1_MouseRightButtonDown" />

you'll get what you need. The code behind is:

private void listBox1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
}

The MouseButtonEventArgs will give you the position via the GetPosition method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!