我在资源字典中定义的字符串为
<x:String x:Key="MyString">This is a resource</x:String>
在我的xaml中。
我在TextBlock中使用此字符串。
有没有一种方法可以使“这是”文本变为粗体?
<TextBlock Text="{StaticResource MyString}"/>
我无法使用“运行”,因为此字符串将被翻译成另一种语言,例如德语。
你可以用你的样式串inline document elements
像<Bold>
,<Italic>
,<Underline>
甚至<Run>
。
special characters
从字符串中逃脱。
使用Inlines
附加属性,该属性将字符串转换为内联元素。
例
<TextBlock local:Inlines.Text="{StaticResource MyString}"/>
MyString的定义如下
<x:String x:Key="MyString"><Bold>This</Bold> is a resource</x:String>
结果将是
内联附加属性的完整源代码
public class Inlines
{
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text",
typeof(string), typeof(Inlines), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, OnTextPropertyChanged));
public static void SetText(DependencyObject @do, string value)
{
@do.SetValue(TextProperty, value);
}
public static string GetText(DependencyObject @do)
{
return (string)@do.GetValue(TextProperty);
}
private static void OnTextPropertyChanged(DependencyObject @do, DependencyPropertyChangedEventArgs e)
{
var textBlock = @do as TextBlock;
if (textBlock == null)
{
throw new InvalidOperationException("This property may only be set on TextBox");
}
var value = GetText(@do);
var text = "<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
$"{value ?? string.Empty}</Span>";
textBlock.Inlines.Clear();
using (var xmlReader = XmlReader.Create(new StringReader(text)))
{
var result = (Span)XamlReader.Load(xmlReader);
textBlock.Inlines.Add(result);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句