Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I have in my Windows Phone application something like that:

C#
string mhm= "Test";
TextBlock K = new TextBlock();
K.Name = "ID";
K.FontSize = 22;
K.Text = mhm;
K.Tap += MyClick;


and

C#
private void MyClick(object sender, GestureEventArgs e)
{
   // How to get string from element mhm ("Test") from sender?
}
Posted

You have to cast sender to its real class or one of the interfaces it implements to use methods and properties.

Here is one way to do it:
C#
private void MyClick(object sender, GestureEventArgs e)
{
    TextBlock txt = sender as TextBlock;
    if( txt == null )
    {
        throw new ArgumentException("MyClick needs first parameter to be a TextBlock");
    }

    string whatEver = txt.Text;
}
 
Share this answer
 
v2
Comments
jakusza 9-Nov-12 8:57am    
Great job. But why does it work?
lukeer 12-Nov-12 4:01am    
Because sender indeed is a TextBlock. It's passed to the event handler routine as object because of a convention that most of the .NET framework adheres to: "First parameter is object sender, so you'll recognize an event handler on first sight." (kind of)

See also: MSDN on the "as" key word[^]
You need to cast the sender with your original control
TextBlock txtBlock = sender as TextBlock;

Thanks,
Rachit
http://agarwalrachit.blogspot.in/[^]
 
Share this answer
 
Please try this code.

C#
private void MyClick(object sender, GestureEventArgs e)
{
   TextBlock txtBlk = new TextBlock();
   txtBlk (TextBlock )sender;
   String txtBlkText = txtBlk.Text;
   
}



Thanks,
Bilaal
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900