Woelund
Woelund

Reputation: 25

XAML - Rendering the contents of a variable

I have the problem that I would like to render the contents of a variable (referenced via the expression "Metatag.Configuration[VisualizerCode].Value" in the code below). The variable contains xaml code (as a string), for example the following contents:

<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>

In my application I have a Grid, in which I would like to render the contents of the variable:

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

Unfortunately, if I run this, the string (= uninterpreted contents of the variable) is printed as text in the Grid, instead of being interpreted (in which case 2 nice, simple borders should be drawn).

How can I get XAML to interpret the contents of the variable and render it ?

Thanks !

Woelund

Upvotes: 1

Views: 401

Answers (1)

King King
King King

Reputation: 63377

You can try using some custom Converter to convert (parse) the string to some instance of the 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();
   }
}

Declare the converter as some resource and used for the Binding in XAML code:

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

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

I hope you know how to declare the prefix local representing the local namespace in which your converter class is declared.

Upvotes: 1

Related Questions