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

2

6

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.

Ripply answered 12/2, 2016 at 7:51 Comment(2)
have you tried string ct = ((sender as Button).Content as TextBlock).Content; ?Anticlockwise
@ericosg, You're the first person submitted right answer. I cordially thank All 3 persons who provided excellent, right answer. I regret that you only wrote as comment not as answer..Thank you so much !Ripply
S
6

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;
Selves answered 12/2, 2016 at 7:54 Comment(1)
So many thanks for your excellent, kindness. All 3 persons brought right answer to me..Have comfortable day !Ripply
F
2

There are few ways to solve your problem. First one is just cast Button content and get the text:

var button = (sender as Button);
if(button == null)
{
    // handle this scenario
}

var textBlockContent = button.Content as TextBlock;
if(textBlockContent == null)
{
    // handle this scenario
}

var ct = textBlockContent.Text;

The second one you can find your TextBlock by name or just reference it if you have event handler in the same control:

var textblock = (TextBlock)this.FindName("YourTextBlockName");
if(textblock == null)
{
    // handle this scenario
}

var ct = textblock.Text;

Also you can try to change your XAML code to store just a text in your button:

<Button Content="YourText" Backround="..." Foreground="..." Style="..." />
Falbala answered 12/2, 2016 at 7:54 Comment(1)
So many thanks for your excellent, kindness. All 3 persons brought right answer to me..Have comfortable day !Ripply

© 2022 - 2024 — McMap. All rights reserved.