【问题标题】:WPF - Rendering a Xaml SegmentWPF - 呈现 Xaml 段
【发布时间】: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 linkXamlReader.Parse方法应该返回TextBlock对象。
  • @Colin XamlReader.Parse 正在返回一个 TextBlock 对象。但是,在实际的 UI 中,它是打印“System.Windows.Controls.TextBlock”而不是实际渲染 TextBlock。我不明白为什么或如何解决它。

标签: c# wpf xaml


【解决方案1】:

TextBlock 的 Text 属性将根据您的 XamlToTextConverter 设置为 TextBlock 对象。由于 Text 属性应该是 string 类型,因此它不知道如何将 TextBlock 显示为字符串。所以默认的方法是使用TextBlock 上的ToString 方法来填充Text 属性,这使得Text 的值为“System.Windows.Controls.TextBlock”。 您似乎想动态呈现 xaml。您可以参考此链接(Loading XAML XML through runtime?) 寻求解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-04-29
    • 1970-01-01
    相关资源
    最近更新 更多