How to add click event to textbox generated in code
I am using silverlight 3 and I would like to create a handler and an event connected to a mouse click in a textbox that was generated in code. Can someone point me in the right direction.
I need to make certain things work when this textbox is clicked.
if you have an example at vb.net that would be even better. thanks to Shannon
a source to share
The following code will simulate a mouse click in a text box created in the code.
TextBox textBox1;
bool mouseDown;
public SilverlightControl1()
{
InitializeComponent();
textBox1 = new TextBox();
textBox1.MouseLeftButtonDown += textBox1_MouseLeftButtonDown;
textBox1.MouseLeftButtonUp += textBox1_MouseLeftButtonUp;
mouseDown = false;
}
void textBox1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (mouseDown)
{
// Do the mouse click here
}
mouseDown = false;
}
void textBox1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mouseDown = true;
}
You probably want to add an extra check that the time between mouse clicks and mouse clicks is less than 500 milliseconds (say) and that the mouse hasn't moved more than a pixel or two between events.
a source to share
I'll just add something to ChrisF's answer and let me know if this is what you want.
TextBox textBox1;
public SilverlightControl1()
{
InitializeComponent();
textBox1 = new TextBox();
textBox1.MouseLeftButtonDown += new MouseButtonEventHandler(textBox1_MouseLeftButtonDown);
}
void textBox1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
InvokeEvent(sender, null);
}
public event EventHandler FireEvent;
public void InvokeEvent(object sender, EventArgs e)
{
EventHandler handler = FireEvent;
if (handler != null) handler(sender, e);
}
///// Here is his vb.net code snippet, please try the code below:
Public Partial Class SilverlightControl1
Inherits UserControl
Private textBox1 As TextBox
Public Sub New()
InitializeComponent()
textBox1 = New TextBox()
AddHandler textBox1.MouseLeftButtonDown, AddressOf textBox1_MouseLeftButtonDown
End Sub
Private Sub textBox1_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
InvokeEvent(sender, Nothing)
End Sub
Public Event FireEvent As EventHandler
Public Sub InvokeEvent(ByVal sender As Object, ByVal e As EventArgs)
Dim handler As EventHandler = FireEvent
RaiseEvent handler(sender, e)
End Sub
End Class
a source to share