1

I have a simple program that implements code discussed in this question to trace mouse movements. However, it seems that the events are only fired if the background colour of the Canvas control is set.

XAML (with the background colour set):

<Window x:Class="SimplePaint.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="501" Width="784">
    <Grid>
        <Canvas Height="402" HorizontalAlignment="Left" Margin="12,12,0,0" Name="PaintCanvas" VerticalAlignment="Top" Width="738" MouseDown="PaintCanvas_MouseDown" MouseMove="PaintCanvas_MouseMove" MouseUp="PaintCanvas_MouseUp" Background="#FFDEF4FF">
            <Polyline x:Name="polyline" Stroke="Black" StrokeThickness="3"/>
        </Canvas>
    </Grid>
</Window>

C#:

private bool drawing = false;

private void PaintCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    this.drawing = true;
}

private void PaintCanvas_MouseMove(object sender, MouseEventArgs e)
{
   if (this.drawing)
        polyline.Points.Add(e.GetPosition(this.PaintCanvas));
}

private void PaintCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    this.drawing = false;
}

This code works. However, if I remove Background="#FFDEF4FF" from the XAML, nothing happens when the program is used. Setting a breakpoint in the event handlers reveals that they do not fire.

Community
  • 1
  • 1
Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
  • It could be that the draw system is linked down to the background draw. I've seen this done in some game code. It could be necessary to start the draw system or else nothing happens. Just a wild guess. – Serguei Fedorov Aug 24 '12 at 18:19

1 Answers1

2

Have you tried "Transparent" for the Background....otherwise your Background=null (i.e. has no background)...and the HitTesting logic of WPF doesn't hit your object.

For an explanation see here:

Community
  • 1
  • 1
Colin Smith
  • 12,375
  • 4
  • 39
  • 47