2011-03-04 217 views
2

我有以下XAML:WPF如何捕捉的ContextMenuClosing事件

<Grid > 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="20"/> 
      <ColumnDefinition Width="*"/> 
      <ColumnDefinition Width="20"/> 
     </Grid.ColumnDefinitions>    
     <local:DropDownButton 
      HorizontalAlignment="Right" 
      Grid.Column="2" 
      Width="18" 
      Style="{StaticResource OrangeButton}" 
      ContextMenuClosing="colorPallete_ContextMenuClosing" 
      x:Name="btnSelectColor">    
      <Polygon Points="0,0,5,4,10,0" Fill="Black"/>            
      <local:DropDownButton.DropDown> 
       <ContextMenu StaysOpen="True" Name="colorPallete" ContextMenuClosing="colorPallete_ContextMenuClosing"> 
        <MenuItem StaysOpenOnClick="True" OverridesDefaultStyle="True" ContextMenuClosing="colorPallete_ContextMenuClosing"> 
         <MenuItem.Header> 
          <local:ColorPickerPopup x:Name="colorPicker" ContextMenuClosing="colorPallete_ContextMenuClosing"/> 
         </MenuItem.Header>             
        </MenuItem>            
       </ContextMenu>           
      </local:DropDownButton.DropDown> 
     </local:DropDownButton>    

     <Rectangle Width="17.5" Stroke="Black" Margin="0" 
        Fill="{DynamicResource CheckerBrush}"/>    

     <Rectangle Width="17.5" Margin="0" Name="rtcColorPreview" /> 
     <TextBox Margin="2,0,0,0" Grid.Column="1" 
       Width="100" BorderThickness="0"      
       Text="{Binding ElementName=colorPicker, Mode=TwoWay, Path=SelectedColorName}"/> 

    </Grid> 

事件處理程序colorPallete_ContextMenuClosing當文本菜單標記colrPallete被關閉不會被調用。我似乎無法弄清楚缺少的東西。

請幫忙! TIA。

回答

2

MSDN documentation ...

文本菜單本身是一個 FrameworkElement的派生類,但 的的ContextMenuClosing事件不會 直接上下文菜單提高。 相反,該事件是由作爲屬性「擁有」上下文菜單 的 元素引發的,並且僅在用戶嘗試關閉UI中的上下文 菜單時引發。

您需要調整您的代碼,以便像您所做的那樣僅在DropDownButton上定義處理程序。如果存在嵌套的ContextMenu,則嵌套的ContextMenu顯然會引發該事件。

<local:DropDownButton ContextMenuClosing="colorPallete_ContextMenuClosing"> 
     ...        
</local:DropDownButton> 

使用Button它看起來像這樣...

<Button ContextMenuClosing="ContextMenu_ContextMenuClosing"> 
    <Button.ContextMenu> 
     <ContextMenu> 
      <MenuItem Header="Go"/> 
     </ContextMenu> 
    </Button.ContextMenu> 
</Button> 

..where當包含MenuItemContextMenu關閉;該事件將被提出並且處理程序將被調用。

不確定什麼DropDownButton控制你正在使用,所以我不能評論DropDown財產是什麼,以及你如何嵌套你的ContextMenu

+0

感謝您的詳細解釋。 – 2011-03-04 21:04:28

+0

感謝您的詳細解釋。 DropDownButton.DropDown只是FrameworkElement.ContextMenu的代理。按照你的建議,事件處理程序仍然沒有被調用。 – 2011-03-04 21:12:33

+0

它是你的控制嗎?第三方? – 2011-03-04 21:16:09