TextBlock
位于Button
内content
。
我想要Text
的{{1}}属性。请建议我如何解决这个问题。
以下代码仅将TextBlock
作为ct
System.Windows.Controls.TextBlock
当然,string ct = (sender as Button).Content.ToString();
的{{1}}实际上是Content
Button
我在stackoverflow中发现了非常类似的情况,但是人们只提供了错误的答案。
答案 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;