[英]C# WPF MVVM Binding commands to hyperlinks in custom text block control
I have a collection of items with a string property.我有一个带有字符串属性的项目集合。 That string property contains text which includes 6 digit numbers in various places like so:
该字符串属性包含文本,其中在不同位置包含 6 位数字,如下所示:
this string 123456 is an example of a set of links 884555 to the following numbers
401177
155879
998552
I want to turn those 6 digit numbers into hyperlinks that when clicked will run a command on the ViewModel passing themselves as parameters.我想将这些 6 位数字转换为超链接,点击后将在 ViewModel 上运行一个命令,将自身作为参数传递。 For example if I click 401177 I want to run HyperlinkCommand on the VM with the string parameter "401177".
例如,如果我单击 401177,我想使用字符串参数“401177”在 VM 上运行 HyperlinkCommand。 I still want to keep the formatting of the original text.
我还是想保留原文的格式。
I figured the best way to do it would be with a custom control based on TextBlock.我认为最好的方法是使用基于 TextBlock 的自定义控件。 Below is the rough structure of my view, the UserControl is bound to the ViewModel, I use a ContentControl to bind to a collection of items with the property "detail", and that is templated with the custom text block bound to the "detail" property of my items.
下面是我的视图的粗略结构,UserControl 绑定到 ViewModel,我使用 ContentControl 绑定到具有“detail”属性的项目集合,并使用绑定到“detail”的自定义文本块进行模板化我的物品的财产。
<UserControl.DataContext>
<VM:HdViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<DataTemplate x:Key="DetailTemplate">
<StackPanel Margin="30,15">
<helpers:CustomTextBlock FormattedText="{Binding detail}"/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentControl Content="{Binding ItemListing}" ContentTemplate="{StaticResource DetailTemplate}" />
</Grid>
I used the code from this question and edited it slightly to generate the following custom control:我使用了this question中的代码并对其进行了轻微编辑以生成以下自定义控件:
public class CustomTextBlock : TextBlock
{
static Regex _regex = new Regex(@"[0-9]{6}", RegexOptions.Compiled);
public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached("FormattedText", typeof(string), typeof(CustomTextBlock), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, FormattedTextPropertyChanged));
public static void SetFormattedText(DependencyObject textBlock, string value)
{
textBlock.SetValue(FormattedTextProperty, value);
}
public static string GetFormattedText(DependencyObject textBlock)
{ return (string)textBlock.GetValue(FormattedTextProperty); }
static void FormattedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TextBlock textBlock)) return;
var formattedText = (string)e.NewValue ?? string.Empty;
string fullText =
$"<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{formattedText}</Span>";
textBlock.Inlines.Clear();
using (var xmlReader1 = XmlReader.Create(new StringReader(fullText)))
{
try
{
var result = (Span)XamlReader.Load(xmlReader1);
RecognizeHyperlinks(result);
textBlock.Inlines.Add(result);
}
catch
{
formattedText = System.Security.SecurityElement.Escape(formattedText);
fullText =
$"<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{formattedText}</Span>";
using (var xmlReader2 = XmlReader.Create(new StringReader(fullText)))
{
try
{
dynamic result = (Span)XamlReader.Load(xmlReader2);
textBlock.Inlines.Add(result);
}
catch
{
//ignored
}
}
}
}
}
static void RecognizeHyperlinks(Inline originalInline)
{
if (!(originalInline is Span span)) return;
var replacements = new Dictionary<Inline, List<Inline>>();
var startInlines = new List<Inline>(span.Inlines);
foreach (Inline i in startInlines)
{
switch (i)
{
case Hyperlink _:
continue;
case Run run:
{
if (!_regex.IsMatch(run.Text)) continue;
var newLines = GetHyperlinks(run);
replacements.Add(run, newLines);
break;
}
default:
RecognizeHyperlinks(i);
break;
}
}
if (!replacements.Any()) return;
var currentInlines = new List<Inline>(span.Inlines);
span.Inlines.Clear();
foreach (Inline i in currentInlines)
{
if (replacements.ContainsKey(i)) span.Inlines.AddRange(replacements[i]);
else span.Inlines.Add(i);
}
}
static List<Inline> GetHyperlinks(Run run)
{
var result = new List<Inline>();
var currentText = run.Text;
do
{
if (!_regex.IsMatch(currentText))
{
if (!string.IsNullOrEmpty(currentText)) result.Add(new Run(currentText));
break;
}
var match = _regex.Match(currentText);
if (match.Index > 0)
{
result.Add(new Run(currentText.Substring(0, match.Index)));
}
var hyperLink = new Hyperlink();
hyperLink.Command = ;
hyperLink.CommandParameter = match.Value;
hyperLink.Inlines.Add(match.Value);
result.Add(hyperLink);
currentText = currentText.Substring(match.Index + match.Length);
} while (true);
return result;
}
}
This is showing the links properly, however I dont know how to bind to the command on my ViewModel.这是正确显示链接,但是我不知道如何绑定到我的 ViewModel 上的命令。 I tested the command and the parameter using a button previously, and the binding was
我之前使用按钮测试了命令和参数,绑定是
Command="{Binding DataContext.HyperlinkCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
CommandParameter="{Binding Content, RelativeSource={RelativeSource Self}}"
So what I am hoping is that I can convert this XAML into C# and attach it to hyperLink.Command =
in my custom control.所以我希望我可以将此 XAML 转换为 C# 并将其附加到我的自定义控件中的
hyperLink.Command =
。 I can't figure out how to access the DataContext of the UserControl that the CustomTextBlock will be placed in.我不知道如何访问将放置 CustomTextBlock 的 UserControl 的 DataContext。
I am not under any illusion that what I am doing is the best or right way of doing things so I welcome any suggestions我并不认为我正在做的事情是最好或正确的做事方式,所以我欢迎任何建议
This is an interesting challenge, which I have solved with new code - coming at the problem in a slightly different way:这是一个有趣的挑战,我用新代码解决了这个问题——以稍微不同的方式解决这个问题:
The code can be found here: https://github.com/deanchalk/InlineNumberLinkControl代码可以在这里找到: https : //github.com/deanchalk/InlineNumberLinkControl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.