RichTextBox中的动态自定义内容

本文关键字:自定义 动态 RichTextBox | 更新日期: 2023-09-27 18:13:17

我希望在一个RichTextBox中显示一个文本+超链接,从代码隐藏或通过Xaml绑定,如果有可能。

目前,我有一个字符串变量与Url(我想非常可点击)绑定到一个TextBlock。我想基本上替换:

<TextBlock Text="{Binding myTextWithUrl}" />

by (in a richhtb:)

<Run Text="partOfTextNonUrl" /><Hyperlink NavigateUri="theUrl" TargetName="whatever" />

显示方式如下:

我有一个ItemsControl模板与自定义对象

<ItemsControl ItemsSource="{Binding FeedResults}">
 <ItemsControl.ItemTemplate>
  <DataTemplate>
   <StackPanel Orientation="Vertical" >
    <my:SearchResultItem />
   </StackPanel>
  </DataTemplate>
 </ItemsControl.ItemTemplate>
</ItemsControl>

这个自定义控件在3个textblock中显示绑定的数据,如上面所示:标题,日期和包含text + url的文本。

我已经有一个从字符串中提取url的方法,我只是不知道如何使用它。我可以动态地生成Run()和Hyperlink(),并将它们添加到段落中,但是如何绑定呢?

或其他解决方案?你会让我很开心的!!

谢谢,Sylvain

RichTextBox中的动态自定义内容

OK。所以很明显,在Silverlight中甚至不允许使用内联超链接。但是你可以自己做!

http://csharperimage.jeremylikness.com/2009/11/inline -超链接- - silverlight 3. - html

不容易——至少不像它应该的那么容易。但它应该能完成任务。

一旦你有能力添加这些运行与超链接,我的方法是这样的。用单个TextBlock (txtContent)创建一个用户控件。设置DataContext="{Binding myTextWithUrl}"。然后在后面的代码中:

public TextWithUrlUserControl()
{
    InitializeComponent();
    this.Loaded += (s, e) =>
                        {
                            foreach(var inline in ParseText(DataContext as string))
                                txtContent.Inlines.Add(inline);
                        };
} 
IEnumerable<Inline> ParseText(string text)
{
    // return list of Runs and Runs with hyperlinks using your URL parsing
    // for demo purposes, just hardcoding it here:
    return new List<Inline>
                {
                    new Run{Text="This text has a "},
                    new Run{Text="URL", RunExtender.NavigateUrl="http://www.google.com/"},
                    new Run{Text="in it!"}
                };    
}

希望对大家有帮助

我会这样做。创建一个ValueConverter,它将获取文本(其中包含URL)。然后在TextBlock中,创建Run和Hyperlink -将两者绑定到文本,两者都使用ValueConverter,但ValueConverter使用不同的参数。

ValueConverter:

public class MyCustomValueConverter: IValueConverter
{    
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(parameter.ToString()== "URL")
        {
            // return the URL part of the string
        }
        else
        {
            // return the non-URL portion of the string
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后你的XAML看起来像这样:

<Run Text="{Binding myTextWithUrl, Converter={StaticResource valueConverter}}"></Run><Hyperlink NavigateUri="{Binding myTextWithUrl, Converter={StaticResource valueConverter}, ConverterParameter=URL}"></Hyperlink>