blob: cdc1938fdc8374bd23d3575649b19ce026b2b0bd (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Documents;
namespace Juick.Classes
{
public class RichTextConverter : IValueConverter
{
static readonly Regex UrlRegex = new Regex(@"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.Compiled);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var stringValue = (string)value;
if (string.IsNullOrEmpty(stringValue))
{
return Enumerable.Empty<Inline>();
}
var result = new List<Inline>();
var index = 0;
foreach (var match in UrlRegex.Matches(stringValue).Cast<Match>())
{
Uri uri = null;
if (!Uri.TryCreate(match.Value, UriKind.Absolute, out uri))
{
continue;
}
if (match.Index > 0)
{
var length = match.Index - index;
if (length > 0)
{
result.Add(new Run { Text = stringValue.Substring(index, length) });
}
}
var hyperLink = new Hyperlink
{
NavigateUri = uri,
TargetName = "_blank"
};
hyperLink.Inlines.Add(uri.Host);
result.Add(hyperLink);
index = match.Index + match.Length;
}
if (index == 0 || index < stringValue.Length - 1)
{
var lastRunText = stringValue.Substring(index);
if (lastRunText.Length > 0)
{
result.Add(new Run { Text = lastRunText });
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
|