2016-12-13 73 views
0

我有几个CheckBox与TextBlock作为内容。 现在我想从每个复选框中读出TextBlock.Text。WPF阅读复选框。内容

如果我读出像checkBox.Content.ToString();这样的内容,我只会得到System.Windows.Controls.TextBlock,这是有道理的。

我也尝试创建一个新的TextBlock并给它的内容,但它没有工作。

TextBlock _tempTBL = new TextBlock(); 
    _tempTBL = checkBox.Content; 

任何帮助,非常感谢。

回答

3
var _tempTBL = (TextBlock) checkBox.Content; //Get handle to TextBlock 
var text = _tempTBL.Text; //Read TextBlock's text 

编辑:

在一个侧面说明,您可以直接设置所需的文本为CheckBox's内容。

checkBox.Content = "Hello World";

而且当你要访问的文本,需要

string text = checkBox.Content;

+0

非常感谢 – mykds

+0

@mykds你也可以直接将CheckBox的内容设置为字符串值,参见我的编辑。 – Marshal

+0

还有一个隐含的演员,是不是? 'Content'返回一个对象类型。 – ps2goat

3

你投的类型为TextBlock

// no need to 'new' it up if you're assigning an existing instance... 
TextBlock _tempTBL = (TextBlock) checkBox.Content; 
+2

没有类型转换,我知道你只是与提供的代码工作,但应注意的是, '= new TextBlock()'是不必要的,因为它只是创建一个在下一行丢弃的“TextBlock”。 – adv12

+0

就是这样。谢谢:-) – mykds

+0

@ adv12有更好的(更清洁)解决方案吗?编辑:啊,我明白你的意思。确定最简单的方法是:TextBlock _tempTBL =(TextBlock)checkBox.Content; – mykds