Mouse event on transparent background

后端 未结 3 1055
臣服心动
臣服心动 2020-12-03 18:00

I have create several canvas with transparent background and wanna make some move event on it.

However, I found that all mouse event (e.g. MouseLeftButtonDown) canno

相关标签:
3条回答
  • 2020-12-03 18:32

    I'm not sure why you get the results you get but it should work fine when the background is transparent (i.e. you explicitly set it to Brushes.Transparent, either through XAML or code). If it is null, WPF will not include it in hit testing, and thus it won't be eligible for mouse events.

    See e.g. http://msdn.microsoft.com/en-us/library/ms752097.aspx (A visual object that is transparent can also be hit test.)

    Most likely you have another UIElement in your element tree that is capturing and handling the mouse event before your canvas sees it (i.e. by setting e.Handled to true)

    0 讨论(0)
  • 2020-12-03 18:34

    Note that there is a difference in setting the background to transparent as opposed to not setting it (or setting it to null). My experience is that hit-testing works on transparent, but not on a null background.

    0 讨论(0)
  • 2020-12-03 18:40

    Transparent DOES react to mouse events, that's the whole point of it, are you sure that you are even hitting the canvas?

    Here's a XAML-only example:

      <Border Width="300" Height="300" BorderBrush="Black" BorderThickness="1">
        <Canvas Background="Transparent">
            <Canvas.Triggers>
                <EventTrigger RoutedEvent="Canvas.MouseLeftButtonDown">
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Brushes.Red}"/>
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Canvas.Triggers>
        </Canvas>
      </Border>
    

    If you set the Background to null, either explicity or implicitly by removing the property it will no longer react.

    0 讨论(0)
提交回复
热议问题