c# – XAML将文本块文本转换为内联
我想在UWP项目中的TextBlock上设置这种文本:
"<Bold>" + variable + "</Bold>" 但是将其设置为Text值不考虑< Bold>标签. 所以我搜索了如何做,唯一的答案是“创建内联并将其添加到您的textBlock”. 所以我正在寻找一个转换器来替换我的text属性,通过inline集合来设置我的textBlock. 我试过这个,但我有一个错误(无法将Binding强制转换为字符串): <TextBlock x:Name="newsArticleSections" Tag="{Binding RelativeSource={RelativeSource Self},Mode=OneWay,Converter={StaticResource TextToRunConverter},ConverterParameter={Binding ArticleSections}}"/> 这是我的转换器: public object Convert(object value,Type targetType,object parameter,string language) { TextBlock textblock = value as TextBlock; textblock.ClearValue(TextBlock.TextProperty); Run run = new Run(); run.Text = (string)parameter; textblock.Inlines.Add(run); return null; } 这只是我探索的方式,但暂时没有结果. 解决方法
@devuxer回答是一个好主意,但仅适用于WPF项目.
所以我用它来制作UWP解决方案并且它有效: 创建一个Formatter类: public class TextBlockFormatter { public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached( "FormattedText",typeof(string),typeof(TextBlockFormatter),new PropertyMetadata(null,FormattedTextPropertyChanged)); public static void SetFormattedText(DependencyObject textBlock,string value) { textBlock.SetValue(FormattedTextProperty,value); } public static string GetFormattedText(DependencyObject textBlock) { return (string)textBlock.GetValue(FormattedTextProperty); } private static void FormattedTextPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { // Clear current textBlock TextBlock textBlock = d as TextBlock; textBlock.ClearValue(TextBlock.TextProperty); textBlock.Inlines.Clear(); // Create new formatted text string formattedText = (string)e.NewValue ?? string.Empty; string @namespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; formattedText = $@"<Span xml:space=""preserve"" xmlns=""{@namespace}"">{formattedText}</Span>"; // Inject to inlines var result = (Span)XamlReader.Load(formattedText); textBlock.Inlines.Add(result); } } 并将此引用添加到您的XAML文件: xmlns:helpers="using:MyProject.Helpers" 要使用格式化程序,只需添加一个TextBlock并在FormattedText上声明您的绑定,如下所示: <TextBlock x:Name="textBlock" helpers:TextBlockFormatter.FormattedText="{Binding Content}"> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |