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

5

一个Button里面有一个TextBlock,作为content

我想要TextBlockText属性。请问如何解决此问题。

以下代码只会返回ctSystem.Windows.Controls.TextBlock

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

当然,按钮内容实际上是一个TextBlock System.Windows.Controls.TextBlock
我在stackoverflow上找到了非常相似的情况,但人们只提供了错误的答案。

2
你尝试过这样写吗?string ct = ((sender as Button).Content as TextBlock).Content; - ericosg
1
@ericosg,你是第一个提交正确答案的人。我衷心感谢所有提供优秀正确答案的3个人。我很遗憾你只留下了评论而不是答案...非常感谢! - Kay Lee
2个回答

5

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

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

1
非常感谢您的优秀和友善。三位都给了我正确的答案。祝您愉快! - Kay Lee

2

有几种方法可以解决您的问题。第一种方法是直接转换 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,或者如果您在同一控件中具有事件处理程序,则可以直接引用它:

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

var ct = textblock.Text;

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

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

非常感谢您的优秀和善良。三位朋友都给了我正确的答案。祝您有一个愉快的一天! - Kay Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接