WPF read Checkbox.Content

笑着哭i 提交于 2019-12-25 04:04:16

问题


I have a couple of CheckBoxes with a TextBlock as content. Now I want to read out the TextBlock.Text from each Checkbox.

If I read out the content like checkBox.Content.ToString(); I only get System.Windows.Controls.TextBlock which kinda makes sense.

I also tried to create a new TextBlock and give it the content but it didn't work.

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

Any help is much appreciated.


回答1:


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

Edit:

On a side note, you can directly set desired text as CheckBox's content.

checkBox.Content = "Hello World";

And when you want to access the text, no type cast is needed

string text = checkBox.Content;




回答2:


You have to cast the type to a TextBlock:

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


来源:https://stackoverflow.com/questions/41129614/wpf-read-checkbox-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!