Friday 26 March 2010

Simple read and display of hardcoded XAML

I found a useful solution to a problem with a path element today. I was trying to dynamically create the path on the fly. I had a lot of rendering issues. So instead I decided to just an XAMLReader to read in some constant text (see below) – worked like a treat! I could have built the path data using line geometry but as the data is static this was a far quicker and easier to implement.

Here is a code snippet..

   1: //A bit of hardcoded xaml for producing the tick
   2: var examplePath = new StringBuilder("<Path xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Data=\"");
   3: examplePath.Append(@"M171,328 C181.07301,342.25397 191,349.12955 191,368 C197.95908,356.40152 197.97304,342.03284 200,328");
   4: examplePath.AppendFormat("\" x:name=\"etick\" Stroke=\"Black\" Fill=\"White\" Stretch=\"Fill\"></Path>");
   5:  
   6: var etick = XamlReader.Load(examplePath.ToString()) as Path;
   7: if (etick != null)
   8: {
   9:     etick.Height = 41;
  10:     etick.Width = 30;
  11:     etick.StrokeThickness = 4;
  12:     evtick.Margin = new Thickness(0,0,10,6);
  13:     etick.VerticalAlignment = VerticalAlignment.Bottom;
  14:     etick.HorizontalAlignment = HorizontalAlignment.Right;
  15:  
  16:     containerGrid.Children.Add(etick);
  17: }

Produces xaml like this dynamically:-


   1: <Path x:Name="etick" Fill="White" Stroke="Black" Data="M171,328 C181.07301,342.25397 191,349.12955 191,368 C197.95908,356.40152 197.97304,342.03284 200,328"
   2:       Height="41" Width="30" StrokeThickness="4" Margin="0,0,10,6" VerticalAlignment="Bottom"
   3: HorizontalAlignment="Right"/>


No comments: