Dynamically generated text with interactive links in it through anchor

I want to create a list consisting of many elements of my own class. One of the properties is text, which may contain one or more links. Usually I use a text binding text box to display this content.

Now I want the text to be parsed for links, and then dynamically make those links available. I found quite some code, for example Add a hyperlink to textblock wpf on how to create a text block with hyperlinks, so I will be fine - but WPF binding is available in the Text property so it does not help me in the end.

So, is there a binding method for a list of elements (ObservableCollection or similar) in the list to have interactive links in the text?

thanks in advance

Sven

+3
source share
1 answer

I have a simple solution.

Using a DataTemplate, you can specify a template for a class, such as LinkItem, which contains your text, and a hyperlink.

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 the LinkItem bundle to the LinkItems collection and you will get a beautiful combination of text and hyperlinks in your list.

You can also add a command to the LinkItem class to make things a little more interesting and link the command to a hyperlink.

 <Hyperlink Command="{Binding HyperlinkCommand}"> .... 
+3
source

Source: https://habr.com/ru/post/899738/


All Articles