Dynamically created text with clickable links in it via binding

南笙酒味 提交于 2019-12-05 14:36:59

I have a simple solution.

Using the DataTemplate, you could specify an template for a class, say LinkItem which contains your text, and a hyper-link.

public class LinkItem
{
    public string Text { get; set; }
    public string Hyperlink { get; set; }

    public LinkItem(string text, string hyperlink)
    {
        Text = text;
        Hyperlink = hyperlink;
    }
}

// XAML Data template
<DataTemplate DataType="{x:Type HyperlinkDemo:LinkItem}">
    <TextBlock>
        <TextBlock Text="{Binding Text}" Margin="1" />
        <Hyperlink>
            <TextBlock Text="{Binding Hyperlink}" Margin="1" />
        </Hyperlink>
    </TextBlock>
</DataTemplate>

// List box definition
<ListBox ItemsSource="{Binding LinkItems}" />

Nice and simple. Just add a bunch of LinkItem to your LinkItems collection and you will get some nice mix of text and hyperlink in your list box.

You could also throw in a command in the LinkItem class to make things a little more interesting and bind the command to the hyperlink.

<Hyperlink Command="{Binding HyperlinkCommand}"> ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!