如何获取TextBlock的Text(TextBlock是Button的内容)

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

a TextBlockButton 内,如 content.

我想要 TextBlockText 属性。请教我如何解决这个问题。

仅以下代码 return ct as System.Windows.Controls.TextBlock

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

当然ButtonContent真的是TextBlockSystem.Windows.Controls.TextBlock
我在 Whosebug 中发现了非常相似的案例,但人们只提供了错误的答案。

由于 ButtonContentTextBlock 您应该将 (sender as Button).Content 视为 TextBlock 然后使用 Text 属性 像这样:

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

解决您的问题的方法很少。第一个只是投射 Button 内容并获取文本:

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;

第二个你可以找到你的 TextBlock by name 或者如果你在同一个控件中有事件处理程序就引用它:

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

var ct = textblock.Text;

您也可以尝试更改 XAML 代码以在按钮中仅存储一个文本:

<Button Content="YourText" Backround="..." Foreground="..." Style="..." />