How to make the WPF Canvas mouse click event work?

The problem with Canvas is that when you click on it, you don’t actually get the click event to occur unless you have a background that is not white.

One trick if you want white is to use white -1 or #FFFFFE or possibly Transparent (unless the parent is not white). So no one can tell it isn’t white, because it is as close to white as can be without actually being white.

Now your click event can occur.

Also you need to make the Canvas focusable.

Example 1 – Getting a Canvas to take keyboard focus from a TextBox with a mouse click

Here is how you make this happen.

  1. First create a new WPF Project.
  2. Add a Canvas and clear the any sizing.
  3. Change the Canvas Background to #FFFFFE.
  4. Set the Canvas to be Focusable.
  5. Add a TextBox in the Canvas.
  6. Create a mouse down event for the Canvas.

MainWindow.xaml

<Window x:Class="TextBoxInCanvas.MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="MainGrid">
 <canvas name="<span class=" span="" class="hiddenSpellError" pre="class ">hiddenspellerror="" pre="">canvas1" Focusable="True" Background="#FFFFFE" MouseDown="canvas1_MouseDown"></canvas>
 <TextBox Height="23" Name="textBox1" Width="120" IsEnabled="True" Canvas.Left="81" Canvas.Top="115"
                     PreviewKeyDown="textBox1_PreviewKeyDown"/>
        </Canvas>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Windows;
using System.Windows.Input;
namespace TextBoxInCanvas
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Keyboard.Focus(canvas1);
        }

        private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (Key.Enter == e.Key)
                Keyboard.Focus(canvas1);
        }
    }
}

Now your click event occurs when the Canvas is clicked and keyboard focus is taken from the TextBox.

Leave a Reply