Search code examples
c#wpfcheckboxtextblock

WPF read Checkbox.Content


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.


Solution

  • 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;