2011-02-11 60 views
3

FlowDocumentReader在其ContextMenu,Copy和Select All中有兩個菜單項。我想一個額外的菜單項添加到它,並嘗試這樣的:向FlowDocumentReader添加菜單項ContextMenu

private void FlowDocumentReader_ContextMenuOpening(object sender, ContextMenuEventArgs e) 
    { 
     flowDocumentReader.ContextMenu.Items.Clear(); 
     MenuItem menuItem = new MenuItem(); 
     menuItem.Header = "Test"; 
     flowDocumentReader.ContextMenu.Items.Add(menuItem); 
    } 

另外我已經試過這樣:

private void FlowDocumentReader_ContextMenuOpening(object sender, ContextMenuEventArgs e) 
    { 
     MenuItem menuItem = new MenuItem(); 
     menuItem.Header = "Test"; 
     flowDocumentReader.ContextMenu.Items.Add(menuItem); 
    } 

,我不清除在上下文菜單中的項目,試圖追加它。這些都不起作用。

我可以創建自己的菜單,如下所示:

private void FlowDocumentReader_ContextMenuOpening(object sender, ContextMenuEventArgs e) 
    { 
     MenuItem menuItem = new MenuItem(); 
     menuItem.Header = "Test"; 
     flowDocumentReader.ContextMenu.Items.Add(menuItem); 
     e.Handled = true; 
     ContextMenu menu = new ContextMenu(); 
     MenuItem a = new MenuItem(); 
     a.Header = "A"; 
     menu.Items.Add(a); 
     MenuItem b = new MenuItem(); 
     b.Header = "B"; 
     menu.Items.Add(b); 
     flowDocumentReader.ContextMenu.Items.Clear(); 
     flowDocumentReader.ContextMenu = menu; 
     menu.IsOpen = true; 
    } 

這會顯示出來,但我想已經是複製和選擇所有的菜單項目,以及A和B.

想法?

回答

0

我到達的解決方案是簡單地在新菜單上重新創建這些MenuItems,並取消顯示通常顯示的內置ContextMenu。有一些內置的ApplicationCommands可以被合併到你自己的自定義的ContextMenu中,並且這個實現非常簡單。

假設我從某種方法GetContextMenu()創建了ContextMenu,下面的事件處理程序會拒絕打開內置的ContextMenu並將調用返回的一個替換爲GetContextMenu(),並添加複製命令(全選相似)。

private void flowDocumentReader_ContextMenuOpening(object sender, ContextMenuEventArgs e) 
{ 
    e.Handled = true; // keeps the built-in one from opening 
    ContextMenu myMenu = GetContextMenu(); 
    MenuItem copyMenuItem = new MenuItem(); 
    copyMenuItem.Command = ApplicationCommand.Copy; 
    copyMenuItem.CommandTarget = myFlowDocument; 
    myMenu.Items.Add(copyMenuItem); 
    ShowMenu(myMenu); 
} 

private void ShowMenu(ContextMenu menu) 
{ 
    menu.Placement = PlacementMode.MousePoint; 
    menu.PlacementRectangle = new Rect(0.0, 0.0, 0.0, 0.0); 
    menu.IsOpen = true; 
} 
5

你也可以爲的FlowDocument爲此在XAML:

<FlowDocument.ContextMenu> 
    <ContextMenu> 
      <MenuItem Header="{Resx Copy}" Command="Copy"/> 
      <MenuItem Header="{Resx SelectAll}" Command="SelectAll"/> 
      <MenuItem Header="{Resx CustomCommand}" Command="{Binding CustomCommand}"/> 
    </ContextMenu> 
</FlowDocument.ContextMenu> 

(頭方便本地化感謝格蘭特Frisken的Resx Extension):)

如果需要應用對於許多FlowDocuments,您還可以將其定義爲某種默認樣式:

<Style TargetType="FlowDocument"> 
    <Setter Property="ContextMenu"> 
     <Setter.Value> 
       <ContextMenu> 
        <MenuItem Header="{Resx Copy}" Command="Copy"/> 
        <MenuItem Header="{Resx SelectAll}" Command="SelectAll"/> 
        <MenuItem Header="{Resx CustomCommand}" Command="{Binding CustomCommand}"/> 
       </ContextMenu> 
     </Setter.Value> 
    </Setter> 
</Style>