【发布时间】:2015-12-31 02:29:57
【问题描述】:
我正在构建一个 UWP 应用程序。 我想要实现的是显示一条推文,如果推文中有任何网址,请将其呈现为超链接文本。 所以我正在做的是浏览文本并查找 url 并将运行分配到一个文本块中,然后将其分配给页面上的文本块。
后面的代码:
TextBlock block = new TextBlock();
Regex url_regex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)" , RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection collection = url_regex.Matches(tweet);
int index = 0;
//for test only
Run r = new Run();
r.Text = "int";
block.Inlines.Add(r);
foreach (Match item in collection)
{
Run run = new Run();
run.Text = tweet.Substring(index , item.Index);
//error occurs here.
block.Inlines.Add(run);
index = item.Index;
run.Text = tweet.Substring(index , item.Length);
Hyperlink h = new Hyperlink();
h.Inlines.Add(run);
block.Inlines.Add(h);
index = item.Index + item.Length;
}
r.Text = tweet.Substring(index , tweet.Length);
block.Inlines.Add(r);
blok = block;
Xaml:
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox Name="input"
PlaceholderText="input here" />
<TextBlock Name="blok"/>
</StackPanel>
我不明白发生了什么,因为测试运行添加工作正常,因为它在 foreach 循环之外。一旦将运行添加到 foreachloop 中的内联中,它就会抛出一个错误,说明:
System.Runtime.InteropServices.COMException: No installed components were detected.
Element is already the child of another element.
互联网上还有其他关于此主题的问题,但我没有得到很好的解决方案。
【问题讨论】:
-
block.Inlines.Add(r) 执行了两次...循环之前和循环之后一次...这是为什么?
-
没有前一个被添加到测试..我猜你在foreach块之外添加了多少次没有错误..
-
只有在 foreach 循环内才会出错
-
您是否尝试过使用构造函数创建 Run 类和初始化?即 run = new Run(strText) ?
-
在循环中,您还将相同的 Run 实例
run添加到超链接元素的内联中。那是行不通的。您必须创建一个新实例。