仅使用 XAML 中的数据绑定对 TextBlock 中的文本进行丰富的格式设置
我正在尝试使用数据绑定格式化推文。我需要做的是根据内容类型拆分推文的文本值。
text = "This is a Tweet with a hyperlink http://www.mysite.com"
我需要向文本值的 http://... 部分添加一些颜色格式。
这是关键,我想仅使用 XAML 数据绑定来完成此操作。
<TextBlock x:Name="Tweet1" FontWeight="Bold" Height="207.236"
LineHeight="55" TextAlignment="Left" TextWrapping="Wrap"
Width="1614.646" Text="{Binding XPath=/statuses/status[2]/text}"
FontSize="56" FontFamily="Segoe Book"
Foreground="{DynamicResource TextColor-Gray}" />
// 需要最终看起来像
<TextBlock x:Name="Tweet1" FontWeight="Bold" ... FontSize="56" FontFamily="Segoe Book">
<Run Foreground="{DynamicResource TextColor-Gray}" >This is a Tweet with a hyperlink</Run>
<Run Foreground="{DynamicResource TextColor-Pink}" >http://www.mysite.com</Run>
</TextBlock>
这是一个我可以用来分割文本值的正则表达式,但我正在尝试严格使用数据绑定。
Regex regUrl = new Regex(@"/http:\/\/\S+/g");
建议?
I am trying to format a Tweet using Data Binding. What I need to do is split the Text value of the tweet based on what type of content it is.
text = "This is a Tweet with a hyperlink http://www.mysite.com"
I need to add some color formatting to the http://... portion of the text value.
Here's the kicker, I'd like to do this using only XAML Data Binding.
<TextBlock x:Name="Tweet1" FontWeight="Bold" Height="207.236"
LineHeight="55" TextAlignment="Left" TextWrapping="Wrap"
Width="1614.646" Text="{Binding XPath=/statuses/status[2]/text}"
FontSize="56" FontFamily="Segoe Book"
Foreground="{DynamicResource TextColor-Gray}" />
// needs to end up looking like
<TextBlock x:Name="Tweet1" FontWeight="Bold" ... FontSize="56" FontFamily="Segoe Book">
<Run Foreground="{DynamicResource TextColor-Gray}" >This is a Tweet with a hyperlink</Run>
<Run Foreground="{DynamicResource TextColor-Pink}" >http://www.mysite.com</Run>
</TextBlock>
Here is a Regex I could use to split the text value, but I'm trying to use strictly DataBinding.
Regex regUrl = new Regex(@"/http:\/\/\S+/g");
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在使用 MVVMLight。我所做的是捕获 TextBlock 的 Loaded 事件,并将其路由到“转换器”。
如果您将此类的实例添加到静态资源中,如下所示:
那么您可以从 TextBlock 调用转换器,如下所示:
如果您不使用 MVVMLight,请道歉。如果你不喜欢,我会把翻译留给读者作为练习。 :)
I'm using MVVMLight. What I've done is to capture the Loaded event of the TextBlock, and route it to a "converter".
If you add an instance of this class to your static resources, like so:
then you can invoke the converter from your TextBlock as follows:
Apologies if you're not using MVVMLight. If you're not, I'll leave the translation as an exercise for the reader. :)
您无法绑定到
Text
并用Run
替换,因为Text
的类型为String
。相反,您需要绑定Inlines
并提供一个转换器来解析文本(例如,使用正则表达式)并生成适当的Inlines
:You can't bind to
Text
and substitute withRun
s becauseText
is of typeString
. Instead, you'd need to bindInlines
and provide a converter that parses the text (using your regex, for example) and produces the appropriateInlines
: