简体   繁体   English

如何从 WPF 将 TextBlock 转换为 c# 中的字符串?

[英]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?如何从 wpf 将TextBlock转换为 c# 中的字符串? 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.但是当我得到 listbox.selecteditem 时,它显然返回了一个文本块,但我需要知道文本块是什么,转换成一个字符串。 how do i do that?我怎么做?

The following region exists for historical reasons.由于历史原因,存在以下区域。


TextBlock.Text ?文本块。 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.如果您现在仍然想不出任何方法将文本从 TextBlock 中取出,那么……我什至不知道那是什么。

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. 根据您的一些评论,您显然尝试根据从 ListBox 获得的 TextBlock 重构信息。 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. TextBlocks 确实(也不应该)包含 object state 信息,如果您拥有的信息不仅仅是文本,您应该使用相应的属性创建一个新的 class,并适当地 绑定到此类集合对象 的数据集合

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. 这样,SelectedItem 将是 class 的 object,其中包含您需要的信息,如果您编辑该信息,UI 将反映这些更改。 TextBlocks are not homeopathic devices . TextBlocks 不是顺势疗法设备

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. 从您在 这个问题上接受的答案来看,在我看来,您只是不想费心学习数据绑定以及使 WPF 成为如此出色平台的所有内容。 Way to cling to error-prone imperative UI creation. 坚持创建容易出错的命令式 UI 的方法。


Take 9001:以 9001 为例:

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

This?这个?

You can't convert a TextBlock to a string.您不能将 TextBlock 转换为字符串。 If you mean the content, look HB's answer.如果您的意思是内容,请查看HB的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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