Dynamically created text with clickable links in it via binding

浪尽此生 提交于 2020-01-02 05:35:09

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/4022109/dynamically-created-text-with-clickable-links-in-it-via-binding

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