I find some solution how select listbox item on right mouse button click, but any solution does not work after I scroll listbox. It possible select listbox on right mouse button, if I scroll also listbox? Any advance?
My code is here:
<ListBox Name="friendsListBox"
ItemsSource="{Binding}"
SelectedItem="Key"
Style="{DynamicResource friendsListStyle}"
PreviewMouseRightButtonUp="ListBox_PreviewMouseRightButtonUp"
PreviewMouseRightButtonDown="ListBox_PreviewMouseRightButtonDown"
Grid.Row="1" MouseRightButtonDown="FriendsListBoxMouseRightButtonDown">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ContextMenu>
<ContextMenu x:Name="FriendContextMenu">
<MenuItem Name="SendRp" Header="Pošli Rp" Click="FriendContextMenuItem_Click" />
<MenuItem Name="SendMsg" Header="Pošli poštu" Click="FriendContextMenuItem_Click"/>
<MenuItem Name="DeleteFriend" Header="Vymaž" Click="FriendContextMenuItem_Click"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
Code behind:
private void ListBox_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
SelectItemOnRightClick(e);
e.Handled = true;
}
private void ListBox_PreviewMouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
SelectItemOnRightClick(e);
FriendContextMenu.PlacementTarget = sender as UIElement;
FriendContextMenu.IsOpen = true;
}
private void FriendsListBoxMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
SelectItemOnRightClick(e);
}
private void SelectItemOnRightClick(System.Windows.Input.MouseButtonEventArgs e)
{
Point clickPoint = e.GetPosition(friendsListBox);
var listBoxItem =
friendsListBox.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;
if (listBoxItem != null)
{
var nPotenialIndex = (int)(clickPoint.Y / listBoxItem.ActualHeight);
if (nPotenialIndex > -1 && nPotenialIndex < friendsListBox.Items.Count)
{
friendsListBox.SelectedItem = friendsListBox.Items[nPotenialIndex];
}
}
}
private void ListBoxItem_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (friendsListBox.SelectedItem!=null)
{
var selectedFriend = (KeyValuePair<string, FriendData>)friendsListBox.SelectedItem;
//MessageBox.Show(selectedFriend.Value.ProfilePhoto.UriSource.OriginalString);
OpenWindow(FriendsData[selectedFriend.Value.Nick.ToLower()]);
}
}