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

时间:2016-02-12 07:51:38

标签: c# wpf button textblock

TextBlock位于Buttoncontent

我想要Text的{​​{1}}属性。请建议我如何解决这个问题。

以下代码仅将TextBlock作为ct

返回
System.Windows.Controls.TextBlock

当然,string ct = (sender as Button).Content.ToString(); 的{​​{1}}实际上是Content Button
我在stackoverflow中发现了非常类似的情况,但是人们只提供了错误的答案。

2 个答案:

答案 0 :(得分:4)

由于Content的{​​{1}}为Button,您应该将TextBlock视为(sender as Button).Content,然后使用TextBlock属性,如下所示:

Text

答案 1 :(得分:2)

解决问题的方法很少。第一个只是转换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; by name,或者如果你在同一个控件中有事件处理程序就引用它:

TextBlock

此外,您可以尝试更改XAML代码以仅在按钮中存储文本:

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

var ct = textblock.Text;