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

发布于 2024-11-10 13:41:21 字数 142 浏览 3 评论 0原文

如何将 TextBlock 从 wpf 转换为 c# 中的字符串?我有一个包含文本块的列表框,以便更改前景色。但是当我得到 listbox.selecteditem 时,它显然返回一个文本块,但我需要知道文本块是什么,转换为字符串。我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请别遗忘我 2024-11-17 13:41:21

以下区域的存在是由于历史原因。


TextBlock.Text

编辑:引用我链接到的文档:

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

如果您现在仍然无法想出任何方法将文本从 TextBlock 中取出,那么...我什至不知道接下来该怎么做。

编辑:

...知道文本块是什么...

这大约是您能得到的最模糊的信息。


开始回答(因为这并不明显)

根据您的一些评论,您显然尝试根据从列表框获得的 TextBlock 重新构建信息。 TextBlock 确实(并且应该)不包含对象状态信息,如果您拥有的信息不仅仅是文本,您应该创建一个具有相应属性的新类,绑定到此类对象的集合,并且datatemplate 集合 适当地。

这样 SelectedItem 将成为包含您需要的信息的类的对象,如果您编辑该信息,UI将反映这些变化。 TextBlock 不是顺势疗法设备

结束答案

您在这个上接受的答案问题 在我看来,您只是不想费心学习数据绑定以及使 WPF 成为如此出色平台的所有内容。坚持容易出错的命令式 UI 创建的方法。


采取 9001:

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

这个?

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?

静谧 2024-11-17 13:41:21

您无法将 TextBlock 转换为字符串。如果你指的是内容,请看HB的回答。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文