簡體   English   中英

僅使用XAML中的DataBinding在TextBlock中豐富文本格式

[英]Rich formatting of text in a TextBlock using only DataBinding in XAML

我正在嘗試使用數據綁定格式化Tweet。 我需要做的是根據它的內容類型拆分推文的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");

建議?

我正在使用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,請道歉。 如果你不是,我會把翻譯留給讀者練習。 :)

您無法綁定到Text並使用Run s替換,因為Text的類型為String 相反,您需要綁定Inlines並提供一個解析文本的轉換器(例如,使用正則表達式)並生成相應的Inlines

<TextBlock Inlines="{Binding XPath=/statuses/status[2]/text, Converter={StaticResource InlineConverter}}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM