Search code examples
c#silverlighttextboxmouseclick-event

Left-button click for Silverlight TextBox


I need TextBox that supports double click, but while trying to code it, i stuck with a problem that Silverlight textbox doesn't raise left-button mouse events if i click inside of text area. So what are possible solutions here? I'm using Silverlight 4.


Solution

  • You should create a custom textbox control that inherits from the default TextBox and override the OnMouseLeftButtonUp method, like this:

    public class MyTextBox : TextBox
    {
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonUp(e);
            // Do your stuff here
        }
    }
    

    If you need to handle the double click, it would be easier to switch to Silverlight 5 that introduced the concept of a click count. Here is a tutorial for handling the double click: http://www.silverlighthostingnews.com/index.php/archives/440 Basically you will just have to do this:

    if(e.ClickCount == 2) {...}
    

    EDIT: here is how to do in Silverlight 4:

    • Create the custom textbox that inherits the default TextBox class and override the mouse events like so:

    -

    public class DoubleClickTextBox : TextBox
    {
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            // Do nothing
        }
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            // Do nothing
        }
    }
    

    -

    DoubleClickExtender dce = new DoubleClickExtender(textBox, 300)
    dce.DoubleClick += new MyEventHandler(dce_DoubleClick);