我正在开发一个WPF应用程序。在这个应用程序中,我有一些XAML段。我需要在TextBlock
中显示XAML段。在我的XAML中,我有以下几行:
<TextBlock Text="{Binding Path=XamlSegment, Converter={StaticResource XamlToTextConverter}}" />
XamlSegment
属性的值将为“-0.275 * x2”。为了在我的UI中呈现此XAML以便显示Superscript,我使用XamlToTextConverter
,其定义如下:
namespace MyApp.Converters
{
public class XamlToTextConverter : IValueConverter
{
private static readonly Regex Regex = new Regex("(<.*?)>(.*)(</.*?>)", RegexOptions.Compiled);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// value looks like this: -0.275*x<Run Typography.Variants="Superscript">2</Run>
var xamlText = value as string;
if (xamlText != null)
{
try
{
xamlText = "<TextBlock>" + xamlText + "</TextBlock>";
var xamlTextWithNamespace = Regex.Replace(xamlText, "$1 xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">$2$3");
return XamlReader.Parse(xamlTextWithNamespace);
}
catch (Exception)
{
return value;
}
}
else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
当这个转换器运行时,我的UI显示“System.Windows.Controls.TextBlock”而不是渲染的XAML。然而,我不知道为什么。如何让我的XamlSegment
在我的界面中呈现?
谢谢
答案 0 :(得分:0)
TextBlock的Text属性将根据您的TextBlock
设置为XamlToTextConverter
对象。由于Text属性的类型应为string
,因此它不知道如何将TextBlock
显示为字符串。因此,完成任务的默认方法是使用ToString
上的TextBlock
方法填充Text属性,该属性使Text的值为“System.Windows.Controls.TextBlock”。
看来你想动态渲染xaml。您可以参考此链接(Loading XAML XML through runtime?)获取解决方案。