c# - 无法将运行添加到 foreach 循环中的文本 block

标签 c# xaml uwp

我正在构建一个 UWP 应用程序。 我想要实现的是显示一条推文,如果推文中有任何 url,则将其呈现为超链接文本。 所以我正在做的是浏览文本并找到 url 并将运行分配到文本 block 中,然后将其分配给页面上的文本 block 。

代码隐藏:

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.

网上还有其他关于这个主题的问题,但我没有找到好的解决方案。

最佳答案

您正在尝试将相同的 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;
}

关于c# - 无法将运行添加到 foreach 循环中的文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34497059/

相关文章:

c# - WPF 多重绑定(bind)到 View 模型

mvvm - UWP 属性在用户控件的依赖属性中更改

xamarin - 如何在 Visual Studio for Mac 上开发 Windows 应用程序

C# Mysql UTF8编码

c# - 尝试在 gridview 标题中的文本框中设置值

c# - 通过 COM 使用 C# 进行 InDesign Server 开发

c# - WPF:无法识别或无法从 XAML 访问整数 CLR 属性

c# - 富域模型实现

xaml - 创建圆形图像 Xaml

带有事件处理程序的 UWP 模板控件