开发者

Dynamically created text with clickable links in it via binding

I do want to create a listview which consists of many items of an own class. One of the properties is a text which can contain one or more links in it. Normally I use a textblock with a binding on Text to get this content displayed.

Now I do want those text being parsed for links and then dynamically make those links clickable. I found quite some code like Add hyperlink to textblock wpf on how to create a textblock with hyperlinks so I would be fine - but the WPF binding is available on the Text property so开发者_运维技巧 this doesn't help me in the end.

So is there a way for binding for a list of items (ObservableCollection or similar) in a listview to have clickable links within text?

Thx in advance

Sven


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}"> ....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜