Search code examples
c#wpfbuttontextblock

How to get the Text of TextBlock (TextBlock is Content of Button)


a TextBlock is inside a Button as content.

I want the Text property of the TextBlock. Please kindly advice how I can solve this.

Below code only return ct as System.Windows.Controls.TextBlock

string ct = (sender as Button).Content.ToString();

Of course, the Content of Button is really a TextBlock System.Windows.Controls.TextBlock
I found very similar case in stackoverflow but people only provided wrong answer.


Solution

  • Since the Content of the Button is TextBlock you should consider (sender as Button).Content as a TextBlock then use the Text property like this:

    string ct = ((sender as Button).Content as TextBlock).Text;