2014-10-30 68 views
0

我可以設置PlacementTargetContextMenu。它始終打開(通過Shift + F10)在列表框的中心。設置ContextMenu通過鍵盤打開的PlacementTarget WPF

我想:

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; 
    } 
} 

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; 
} 

但它仍然不能按預期工作。 (我期望它顯示在選定的itemlistbox的中心)

有什麼建議嗎?

+0

你能告訴更確切的是什麼問題嗎?有什麼異常?或者只是ContextMenu仍然顯示在中心? – 2014-10-30 08:10:04

+0

仍然顯示在列表框的中心,但我期望在選定listboxitem的中心 – maskalek 2014-10-30 08:20:29

回答

1

我剛剛試過你的代碼。問題是,一旦設置爲ListBox,您就無法更改ContextMenuPlacementTarget。這意味着ListBox始終設置爲ContextMenu的PlacementTarget。我明白,ContextMenu實際上用於所選項目。那麼爲什麼不把它設置爲每個項目?然後它預計工作。試試這個:

<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> 

這裏沒有涉及任何代碼。只要像上面那樣改變你的XAML。

+0

是的,謝謝。它會工作:)但我想有沒有重寫我的contextmenu相同的行爲。所有綁定將無法正常工作,我將不得不重新編寫它:(希望有其他解決方案 – maskalek 2014-10-30 09:08:36

+0

@maskalek我認爲只有一點變化才能使綁定工作,您可以舉一些你在ContextMenu上設置綁定的例子嗎? – 2014-10-30 10:21:01