Monday, December 14, 2009

Five Minute Silverlight 4 Aides-Memoire #6 – Right Mouse Event Support

<Popup x:Name="PopupMenu" IsOpen="False">
    <ListBox x:Name="MenuItems">
        <ListBoxItem Content="Item 1" />
        <ListBoxItem Content="Item 2" />
        <ListBoxItem Content="Item 3" />
        <ListBoxItem Content="Item 4" />
    </ListBox>
</Popup>


public MainPage()
{
    InitializeComponent();
    MouseRightButtonDown += (s, e) => e.Handled = true;
    MouseRightButtonUp += MainPage_MouseRightButtonUp;
    MenuItems.MouseLeftButtonUp += MenuItems_MouseLeftButtonUp;
}


void MainPage_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    this.PopupMenu.HorizontalOffset = e.GetPosition(this).X;
    this.PopupMenu.VerticalOffset = e.GetPosition(this).Y;
    this.PopupMenu.IsOpen = true;
}

void MenuItems_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    PopupMenu.IsOpen = false;
    System.Diagnostics.Debug.WriteLine(((sender as ListBox).SelectedItem as ListBoxItem).Content);
}

No comments: