html wpf hyperlink textblock

html - Añadir hipervínculo al bloque de texto wpf



hyperlink textblock (2)

La visualización es bastante simple, la navegación es otra cuestión. XAML va así:

<TextBlock Name="TextBlockWithHyperlink"> Some text <Hyperlink NavigateUri="http://somesite.com" RequestNavigate="Hyperlink_RequestNavigate"> some site </Hyperlink> some more text </TextBlock>

Y el controlador de eventos que inicia el navegador predeterminado para navegar a su hipervínculo sería:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { System.Diagnostics.Process.Start(e.Uri.ToString()); }

Editar: Para hacerlo con el texto que tienes de la base de datos, tendrás que analizar el texto de alguna manera. Una vez que conozca las partes textuales y las partes con hipervínculo, puede crear contenido de bloques de texto dinámicamente en el código:

TextBlockWithHyperlink.Inlines.Clear(); TextBlockWithHyperlink.Inlines.Add("Some text "); Hyperlink hyperLink = new Hyperlink() { NavigateUri = new Uri("http://somesite.com") }; hyperLink.Inlines.Add("some site"); hyperLink.RequestNavigate += Hyperlink_RequestNavigate; TextBlockWithHyperlink.Inlines.Add(hyperLink); TextBlockWithHyperlink.Inlines.Add(" Some more text");

Saludos, tengo un texto en una base de datos y es el siguiente:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tellus nisl, venenatis et pharetra ac, tempor sed sapiens. Integral pellentesque blandit velit, en tempus urna semper sit amet. Duis mollis, libero ut consectetur interdum, massa tellus posuere nisi, eu aliquet elit lacus nec erat. Praesent a commodo quam. ** [a href = '' http://somesite.com ''] algún sitio [/ a] ** Suspender en nisi sit amet massa molestie gravie fe fe ac ac. Phasellus ac mauris ipsum, vel auctor odio

Mi pregunta es: ¿Cómo puedo mostrar un Hyperlink en un TextBlock ? No quiero usar un control webBrowser para este propósito. Tampoco quiero usar este control: http://www.codeproject.com/KB/WPF/htmltextblock.aspx también


Puede usar Regex con un convertidor de valores en tal situación.

Use esto para sus requerimientos (idea original de here ):

private Regex regex = new Regex(@"/[a/s+href=''(?<link>[^'']+)''/](?<text>.*?)/[/a/]", RegexOptions.Compiled);

Esto coincidirá con todos los enlaces en su cadena que contiene enlaces, y creará 2 grupos con nombre para cada coincidencia: link y text

Ahora puedes iterar a través de todos los partidos. Cada partido te dará una

foreach (Match match in regex.Matches(stringContainingLinks)) { string link = match.Groups["link"].Value; int link_start = match.Groups["link"].Index; int link_end = match.Groups["link"].Index + link.Length; string text = match.Groups["text"].Value; int text_start = match.Groups["text"].Index; int text_end = match.Groups["text"].Index + text.Length; // do whatever you want with stringContainingLinks. // In particular, remove whole `match` ie [a href=''...'']...[/a] // and instead put HyperLink with `NavigateUri = link` and // `Inlines.Add(text)` // See the answer by Stanislav Kniazev for how to do this }

Nota: use esta lógica en su convertidor de valores personalizado ConvertToHyperlinkedText .