Reputation: 952
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.
Upvotes: 6
Views: 5355
Reputation: 8892
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="..." />
Upvotes: 2
Reputation: 39956
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;
Upvotes: 6