【发布时间】:2016-02-15 22:19:26
【问题描述】:
我正在开发一个 WPF 应用程序。在这个应用程序中,我有一些 XAML 段。我需要在TextBlock 中显示 XAML 段。在我的 XAML 中,我有以下行:
<TextBlock Text="{Binding Path=XamlSegment, Converter={StaticResource XamlToTextConverter}}" />
XamlSegment 属性的值类似于“-0.275*x2”。为了尝试在我的 UI 中呈现此 XAML 以便显示上标,我使用了 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 在我的 UI 中呈现?
谢谢
【问题讨论】:
-
根据this link,
XamlReader.Parse方法应该返回TextBlock对象。 -
@Colin
XamlReader.Parse正在返回一个TextBlock对象。但是,在实际的 UI 中,它是打印“System.Windows.Controls.TextBlock”而不是实际渲染 TextBlock。我不明白为什么或如何解决它。