【问题标题】:XAML - Rendering the contents of a variableXAML - 呈现变量的内容
【发布时间】:2014-11-17 14:57:59
【问题描述】:

我有一个问题,我想渲染一个变量的内容(通过下面代码中的表达式“Metatag.Configuration[VisualizerCode].Value”引用)。该变量包含 xaml 代码(作为字符串),例如以下内容:

<Grid>
<Canvas> 
  <Border Canvas.Top="0" Canvas.Left="390" Width="50" Height="100" BorderThickness="2" BorderBrush="Black"> </Border>
  <Border Canvas.Top="100" Canvas.Left="340" Width="100" Height="50" BorderThickness="2" BorderBrush="Black"> </Border>
</Canvas>
</Grid>

在我的应用程序中,我有一个网格,我想在其中呈现变量的内容:

<Grid Margin="0,10,0,0" Visibility="Visible">
  <ContentControl Content="{Binding Path=Metatag.Configuration[VisualizerCode].Value}">
</ContentControl>

不幸的是,如果我运行它,字符串(= 变量的未解释内容)会在网格中打印为文本,而不是被解释(在这种情况下应该绘制 2 个漂亮、简单的边框)。

如何让 XAML 解释变量的内容并呈现它?

谢谢!

沃伦德

【问题讨论】:

标签: c# wpf xaml


【解决方案1】:

您可以尝试使用一些自定义Converter 将字符串转换(解析)为Grid 的某个实例:

public class StringToElementConverter : IValueConverter {
   public object Convert(object value, Type targetType, object parameter,
                                       CultureInfo culture){
      var pc = new ParserContext();
      pc.XmlnsDictionary[""] = 
                   "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
      pc.XmlnsDictionary["x"] = "http://schemas.microsoft.com/winfx/2006/xaml";
      return XamlReader.Parse(System.Convert.ToString(value), pc);
   }
   public object ConvertBack(object value, Type targetType, object parameter, 
                                           CultureInfo culture){
      throw new NotImplementedException();
   }
}

将转换器声明为某种资源并用于 XAML 代码中的绑定:

<Window.Resources>
   <local:StringToElementConverter x:Key="elementConverter"/>
</Window.Resources>

<ContentControl Content="{Binding Metatag.Configuration[VisualizerCode].Value,
                          Converter={StaticResource elementConverter}}"/>

我希望你知道如何声明前缀 local 代表你的转换器类被声明的本地命名空间。

【讨论】:

  • 难以置信...我印象深刻!非常感谢 - 就像一个魅力!
  • 您可以直接使用XamlReader.Parse 而不是创建ParserContext 并定义自己的命名空间,包括默认命名空间..
  • @lll 我用XamlReader.Parse 体验过,没有使用ParserContext 我必须在字符串中包含xmlns 就在字符串中 ,比如像这样"&lt;Grid xmlns=\"...\" xmlns:x=\"...\"&gt;..."。您可以自己尝试一个简单的演示。
  • @KingKing 我可以看到它没有被添加到 Child 标记中,但 Root 标记将具有命名空间。
  • @lll 我不明白你的意思。这里的问题是是否使用 ParserContext,如果使用它,按照我的回答执行,如果不使用它,按照我上面的评论执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多