![](/img/trans.png)
[英]Save RichTextBox content containing both images and custom token elements
[英]Dynamic custom content in RichTextBox
我希望从代码背后或通过Xaml绑定的RichTextBox中显示文本+超链接。
目前,我有一个带有Url的字符串变量(我非常想使其可单击)绑定到TextBlock。 我想基本上取代:
<TextBlock Text="{Binding myTextWithUrl}" />
通过(在richTB中:)
<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(),并将它们添加到段落中,但是如何绑定?
或任何其他解决方案? 你会让我开心的!
谢谢,西尔万
我会做这样的事情。 创建一个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>
好。 因此,显然在Silverlight中甚至不允许内联超链接。 但是你可以自己做!
http://csharperimage.jeremylikness.com/2009/11/inline-hyperlinks-in-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!"}
};
}
希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.