WPF多次鼠标单击禁用鼠标事件

时间:2016-07-07 18:06:50

标签: c# wpf datagrid mouseevent contextmenu

我遇到了问题:我有数据网格,我想在鼠标左键单击时打开上下文菜单。所以我在其中创建了datagrid和template列:

<DataGridTemplateColumn CellStyle="{StaticResource StageNameCellStyle}"/>

细胞风格:

<Style x:Key="StageNameCellStyle" TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel>
                    <i:Interaction.Behaviors>
                        <local:OpenContextMenuLeftBehavior/>
                    </i:Interaction.Behaviors>
                    <TextBlock Text="{Binding Name}" TextWrapping="Wrap" DockPanel.Dock="Top"/>
                    <DockPanel.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="1"
                                      Command="{Binding Data.AddReportCommand, Source={StaticResource WindowViewModel}}">
                                <MenuItem.Icon>
                                    <Image Style="{StaticResource TypicalImageStyle}" Source="../Resources/Images/report_add.png"/>
                                </MenuItem.Icon>
                            </MenuItem>
                        </ContextMenu>
                    </DockPanel.ContextMenu>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

它的行为:

public class OpenContextMenuLeftBehavior : Behavior<FrameworkElement>
{
    protected override void OnAttached()
    {
        AssociatedObject.PreviewMouseLeftButtonUp += OpenContextMenu;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewMouseLeftButtonUp -= OpenContextMenu;
    }

    void OpenContextMenu(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left) {
            ((FrameworkElement)sender).ContextMenu.PlacementTarget = (FrameworkElement)sender;
            ((FrameworkElement)sender).ContextMenu.IsOpen = true;
        }
    }
}

所以,问题是: 当我在该单元格上多次单击时,首先点击一下即可打开菜单,但随后停止并且根本不会触发鼠标事件。 但是如果我将光标移出窗口并将其返回 - 它将再次起作用。 请帮帮我。

0 个答案:

没有答案