左键单击打开按钮ContextMenu

时间:2015-02-07 01:07:29

标签: c# .net wpf

我有一个带有上下文菜单的按钮,我的要求是在左键单击上显示上下文菜单

问题是当上下文菜单打开时,<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;

}

这个问题有没有简单的解决方案?

1 个答案:

答案 0 :(得分: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);
        }
    }