Click here to Skip to main content
15,899,124 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So I'm stumbling upon some issues where the standard way of creating XAML from C# seems to refuse to do things my way, so I was wondering if there were a way to add a string containing XAML from C#, not unlike the way one would in PHP using echo or pring commands to dump html.

thanks for any help!

-frank
Posted
Updated 7-Apr-12 12:46pm
v2

Here is what I do:

XML
string Xaml= @"<SolidColorBrush xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Color=""AliceBlue""/">;
          StringReader stringReader = new StringReader(Xaml);
          System.Xml.XmlReader xmlReader = new System.Xml.XmlTextReader(stringReader);
          Brush rslt = XamlReader.Load(xmlReader) as Brush;

/// <summary>
      /// Allow the UI dispatcher thread to spin
      /// </summary>
      private static void DoEvents()
      {
          DispatcherFrame frame = new DispatcherFrame(true);
          Dispatcher.CurrentDispatcher.BeginInvoke
              (
                  DispatcherPriority.Background,
                  (SendOrPostCallback)delegate(object arg)
                  {
                      var dispatcherFrame = arg as DispatcherFrame;
                      dispatcherFrame.Continue = false;
                  },
                  frame
              );
          Dispatcher.PushFrame(frame);
      }
 
Share this answer
 
Comments
Frank R. Haugen 8-Apr-12 7:50am    
Somewhat less elegant than the one I found, but I still like it!
So my awesome D&D buddy "Gygaxiss the Fayhunter" just sent me to: http://oldschooldotnet.blogspot.com/2008/11/dynamically-dding-xaml-strings-from-c.html[^]

It had exactly what I was looking for so sorry for posting "needlessly".


Giving a fully fledge explaination of the solution:

simply do this:

C#
// create the XAML-code as a string
    string newEllipse = "<Ellipse xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Stroke='Black' Fill='Red' Height='30' Width='30' Margin='10,10,10,10'></Ellipse>";

// Make string valid XML
    XmlReader reader = XmlReader.Create(new StringReader(newEllipse));

// Add the XAML to the design
    RootElementName.Children.Add((Ellipse)XamlReader.Load(reader));

Apparently there are namespace issues if one does not add the "xmlns...".

-frank
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900