WPF行为MouseDown不会触发

时间:2019-03-01 22:38:53

标签: c# wpf expression-blend-4

我正在学习Microsoft.Expression.Interactions.WPF。我正在尝试将行为附加到网格的MouseDown事件。 OnAttached方法被调用,但是我的行为从未收到MouseDown事件。

XAML

<Window x:Class="SequenceDiagramViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SequenceDiagramViewer"
        xmlns:ineractivity="http://schemas.microsoft.com/expression/2010/interactivity"
        mc:Ignorable="d"
        Title="Sequence Diagram Viewer" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>
    <Grid>
        <ineractivity:Interaction.Behaviors>
            <local:MouseClick />
        </ineractivity:Interaction.Behaviors>
    </Grid>
</Window>

C#

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace SequenceDiagramViewer
{
  public class MouseClick : Behavior<FrameworkElement>
  {
    protected override void OnAttached()
    {
      Console.WriteLine("OnAttached called");
      AssociatedObject.MouseDown += AssociatedObject_MouseDown;
    }

    private void AssociatedObject_MouseDown(object sender, MouseButtonEventArgs e)
    {
      Console.WriteLine("MouseDown called");
    }

    protected override void OnDetaching()
    {
      Console.WriteLine("OnDetaching called");
      AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
    }
  }
}

在我的控制台输出中,我仅得到OnAttached called。另外,当我在AssociatedObject_MouseDown中放置一个断点时,它从未被命中,而OnAttached却被命中。我该如何使事件符合我的行为?

1 个答案:

答案 0 :(得分:0)

我的网格背景是透明的。一旦将网格XAML更改为此:

<Grid Background="White">
    <interactions:Interaction.Behaviors>
        <local:MouseClick />
    </interactions:Interaction.Behaviors>
</Grid>

然后我开始获取鼠标按下事件。