Reputation: 505
I can's set PlacementTarget
for ContextMenu
. It is always opened (via Shift+F10) in the center of listbox.
I tried:
private void listBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Shift &&
(e.Key == Key.F10 || e.SystemKey == Key.F10)){
var listBox = sender as System.Windows.Controls.ListBox;
listBox.ContextMenu.PlacementTarget = listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem) as ListBoxItem;
}
}
and
private void listBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var listBox = sender as System.Windows.Controls.ListBox;
listBox.ContextMenu.PlacementTarget = listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem) as ListBoxItem;
}
But it still doesn't work as expected. (I expect it is shown in the center of selected itemlistbox)
Any suggestions?
Upvotes: 0
Views: 615
Reputation: 63377
I've just tried your code. The problem is you cannot change the PlacementTarget
of the the ContextMenu
once it is set to the ListBox
. That means the ListBox
is always set as PlacementTarget
of the ContextMenu. I understand that that ContextMenu is in fact used for the selected item. So why not set it for each item? Then it works expectedly. Try this:
<ListBox ItemsSource="some_source_here"/>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<!-- your ContextMenu here -->
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
There is not any code behind involved here. Just change your XAML like above.
Upvotes: 1