2015-02-07 133 views
0

我有一個上下文菜單按鈕,我的要求是,以顯示在左側點擊右鍵菜單左鍵打開按鈕文本菜單點擊

的問題是,<ContextMenu ItemsSource="{Binding LineItems}"未更新/刷新上下文菜單時打開。但是如果我右擊第一,項目被加載罰款

XAML

<Button x:Name="BtnMessageChannel" Click="BtnMessageChannel_Click" Grid.Row="0" Grid.Column="2" Height="23" Width="23" ToolTip="Message Channel" > 
    <Button.ContextMenu> 
     <ContextMenu ItemsSource="{Binding LineItems}" x:Name="CtxMessageChannel"> 
      <ContextMenu.Resources> 
       <Image x:Key="img" Source="{Binding Icon}" x:Shared="false"/> 
       <Style TargetType="{x:Type MenuItem}"> 
        <Setter Property="Header" Value="{Binding DisplayName}"/> 
        <Setter Property="Icon" Value="{StaticResource img}"> 
        </Setter> 
       </Style> 
      </ContextMenu.Resources> 
     </ContextMenu> 
    </Button.ContextMenu> 
    <Image Source="Images/mail_send.png" HorizontalAlignment="Left" Width="16" /> 
</Button> 

代碼隱藏

private void BtnMessageChannel_Click(object sender, RoutedEventArgs e) 
{ 
    BtnMessageChannel.ContextMenu.GetBindingExpression(ContextMenu.ItemsSourceProperty) 
      .UpdateTarget(); 
    BtnMessageChannel.ContextMenu.Visibility = Visibility.Visible; 
    BtnMessageChannel.ContextMenu.IsOpen = true; 

} 

是否有這個問題的任何簡單的解決辦法?

回答

4

一個簡單的解決方案是更新您的按鈕事件處理程序以模擬右鍵單擊,如果上下文菜單當前未打開。

private void BtnMessageChannel_Click(object sender, RoutedEventArgs e) 
    { 
     if (!BtnMessageChannel.ContextMenu.IsOpen) 
     { 
      e.Handled = true; 

      var mouseRightClickEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Right) 
      { 
       RoutedEvent = Mouse.MouseUpEvent, 
       Source = sender, 
      }; 
      InputManager.Current.ProcessInput(mouseRightClickEvent); 
     } 
    }