简体   繁体   中英

How do you convert a TextBlock to a string in c# from WPF?

How do you convert a TextBlock to a string in c# from wpf? i have a listbox that contains a textblock in order to change the foreground color. but when i get listbox.selecteditem, it obviously returns a textblock, but i need to know what the textblock is, converted into a string. how do i do that?

The following region exists for historical reasons.


TextBlock.Text ?

Edit: To quote the documentation i linked to:

TextBlock textBlock = new TextBlock();
textBlock.Text = "The text contents of this TextBlock.";

If you still cannot think of any way to get the text out of a TextBlock now then... i don't even know what then.

Edit:

...know what the textblock is...

This is about as vague as you can get.


Begin Answer (Since this was not apparent)

Based on some of your comments you apparently try to recostruct information based on the TextBlock you get from a ListBox. TextBlocks do (and should) not contain object state information, if you have more information than just text you should create a new class with the respective properties, bind to a collection of such objects, and datatemplate the collection appropriately.

That way the SelectedItem will be an object of the class which contains the information you need, and if you edit that information the UI will reflect those changes. TextBlocks are not homeopathic devices .

End Answer

From what answer you accepted on this question it looks to me like you just don't want to bother learning about data binding and all the things that make WPF such a great platform. Way to cling to error-prone imperative UI creation.


Take 9001:

 string text = ((TextBlock)listbox.SelectedItem).Text;

This?

You can't convert a TextBlock to a string. If you mean the content, look HB's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM