我正在尝试使用数据绑定格式化推文。我需要做的是根据推文的内容类型拆分推文的Text值。
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>
这是我可以用来分割文本值的正则表达式,但我正在尝试严格使用DataBinding。
Regex regUrl = new Regex(@"/http:\/\/\S+/g");
建议?
答案 0 :(得分:2)
我正在使用MVVMLight。我所做的是捕获TextBlock的Loaded事件,并将其路由到“转换器”。
using System.Collections.Generic;
using System.Windows.Documents;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Command;
namespace Converters
{
public class MyInlineConverter
{
public RelayCommand<TextBlock> ConvertTextToInlinesCommand { get; private set; }
public MyInlineConverter()
{
ConvertTextToInlinesCommand = new RelayCommand<TextBlock>(textBlock => convertTextToInlines(textBlock));
}
private static void convertTextToInlines(TextBlock textBlock)
{
foreach (Run run in textToInlines(textBlock.Text))
textBlock.Inlines.Add(run);
}
private static IEnumerable<Run> textToInlines(string text)
{
List<Run> retval = new List<Run>();
// Perform your conversion here.
return retval;
}
}
}
如果您将此类的实例添加到静态资源中,请执行以下操作:
<converters:TMTInlineConverter x:Key="InlineConverter" />
然后您可以按如下方式从TextBlock调用转换器:
<TextBlock Text="{Binding MyPath}" TextWrapping="Wrap">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmdex:EventToCommand Command="{Binding Source={StaticResource InlineConverter}, Path=ConvertTextToInlinesCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
如果你没有使用MVVMLight,请道歉。如果你不是,我会把翻译留给读者练习。 :)
答案 1 :(得分:1)
您无法绑定到Text
并替换为Run
,因为Text
的类型为String
。相反,您需要绑定Inlines
并提供一个解析文本的转换器(例如,使用正则表达式)并生成相应的Inlines
:
<TextBlock Inlines="{Binding XPath=/statuses/status[2]/text, Converter={StaticResource InlineConverter}}"/>