如何通过 TextBlock 文本值设置 TextBlock 的 Foreground 属性?
是否可以通过 TextBlock 文本值设置 TextBlock 的前景属性? 例如:文本值为 Mike,前景属性为 Black,值为 Tim,属性值为 green 等。我用 google 搜索,但没有找到任何解决方案。
it’s possible set the foreground property of a TextBlock by TextBlock text value?
For example: Text value is Mike, foreground property is Black, value is Tim, property value is green, etc. I search with google, but I don’t find any solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望灵活地做一些聪明的事情,例如动态地将文本映射到颜色等,您可以使用 Converter 类。我假设文本设置为绑定到某些内容,您可以通过自定义转换器绑定到前台中的相同内容:
您的转换器将被定义为如下所示:
显然,您可以使用更智能的逻辑来代替简单的 switch 语句处理新值等。
If you want the flexibility to do something smart, such as dynamically map texts to colors and so on, you could use a Converter class. I am assuming the text is set to bind to something, you could bind to the same something in Foreground but through a custom converter:
Your converter would be defined something like this:
Obviously, instead of the simple switch statement you could have smarter logic to handle new values and such.
您有一个模型视图(实现 INotifyPropertyChanged),其中 Text 作为属性,前景色作为属性,让文本块将这两个属性绑定到模型视图。颜色属性可以取决于文本属性。
you have a model view (implementing INotifyPropertyChanged) that has the Text as a property and the foreground color as a property, have the textblock bind those two properties to the model view. the color property can depend on the text property.
根据投票评论的数量,我正在修改 @danut-enachioiu 的答案,以使用
Brushes
而不是Colors
来实现解决方案,以便返回的值与WPF 元素属性的类型。这是修改后的代码...
Based on the number of voted comments, I am revising the answer from @danut-enachioiu to implement the solution using
Brushes
, instead ofColors
so that the value returned will match the type of the WPF Element Property.Here is the revised code...