【问题标题】:Cannot add run to a textblock in foreach loop无法在 foreach 循环中将运行添加到文本块
【发布时间】: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 添加到超链接元素的内联中。那是行不通的。您必须创建一个新实例。

标签: c# xaml uwp


【解决方案1】:

您正在尝试将相同的 Run 元素分配给 2 个父级:TextBlockHyperlink

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;

虽然这是 2 次不同的运行,但请将循环更改为:

foreach (Match item in collection)
{

    Run runRegularText = new Run();
    runRegularText.Text = tweet.Substring(index, item.Index);
    block.Inlines.Add(runRegularText);

    index = item.Index;

    Run runHyperlink = new Run();
    runHyperlink.Text = tweet.Substring(index, item.Length);
    Hyperlink h = new Hyperlink();
    h.Inlines.Add(runHyperlink);
    block.Inlines.Add(h);

    index = item.Index + item.Length;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-30
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多