我找到一些解决方案如何在鼠标右键单击上选择列表框项目,但滚动列表框后任何解决方案都不起作用。如果我也滚动列表框,可以在鼠标右键上选择列表框吗?任何进步?
我的代码在这里:
<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>
代码背后:
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()]);
}
}
答案 0 :(得分:4)
要在右键单击中选择项目,您可以改为执行此操作。它适用于滚动
private void SelectItemOnRightClick(System.Windows.Input.MouseButtonEventArgs e)
{
Point clickPoint = e.GetPosition(friendsListBox);
object element = friendsListBox.InputHitTest(clickPoint);
if (element != null)
{
ListBoxItem clickedListBoxItem = GetVisualParent<ListBoxItem>(element);
if (clickedListBoxItem != null)
{
friendsListBox.SelectedItem = clickedListBoxItem.Content;
}
}
}
public T GetVisualParent<T>(object childObject) where T : Visual
{
DependencyObject child = childObject as DependencyObject;
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}