Skip to content

Getting a MouseLeftButtonDown or MouseLeftButtonUp Event From Your TextBox

One of the nifty little tricks I got working in my attempt to update my Silverlight Color Picker was that I wanted to have the entire content of a TextBox to select when I clicked on it. Imagine my surprise when clicking on the TextBox didn’t fire either a MouseLeftButtonUp or a MouseLeftButtonDown event!

This stunned me a little bit. Turns out there is a big discussion about this over at the Silverlight Forum. Long story short, I needed to add this code to my project (you’ll see it in my Color Picker project if you download it).

Add this code to your MyPage.xaml.cs file:

public class TextBoxClickable : TextBox
{
     protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
     {
           base.OnMouseLeftButtonDown(e);
           e.Handled = false;
     }

     protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
     {
           base.OnMouseLeftButtonUp(e);
           e.Handled = false;
     }
}

Your XAML should define your namespace:

<UserControl x:Class=”MyProjectName.MyPage
      xmlns:clickable=”clr-namespace:MyPage“>

And you can use your new clickable TextBox like this:

<clickable:TextBoxClickable MouseLeftButtonDown=”TextBox_SelectAll/>

If you’re like me and want to select everything in the TextBox with a single click, your method will look like this:

private void TextBox_SelectAll(object sender, MouseButtonEventArgs e)
{
     TextBox selectionBox = (TextBox)sender;
     selectionBox.SelectAll();
}

That’s it. I’ll post my updated color pickers in a couple hours.