3
votes

I am writing a windows 8.1 phone runtime app. I have a file in my assets which has Xaml content in it. When a button is pressed, I want to make the contents of a Stackpanel as defined by the Xaml in the file.

I searched around a bit and found that we can read the Xaml file in a string and pass it to XamlReader class which can then be used to assign a new Xaml to the StackPanel. The method I am referring to is here and the code is written below too.

string xaml =
"<Ellipse Name=\"EllipseAdded\" Width=\"300.5\" Height=\"200\" 
Fill=\"Red\" \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>";
object ellipse = XamlReader.Load(xaml);

//stackPanelRoot is the visual root of a Page in existing XAML markup already loaded by the appmodel
stackPanelRoot.Children.Add(ellipse as UIElement);

//walk the tree using XLinq result and cast back to a XAML type to set a property on it at runtime
var result = (from item in stackPanelRoot.Children
  where (item is FrameworkElement) 
  && ((FrameworkElement) item).Name == "EllipseAdded"
  select item as FrameworkElement).FirstOrDefault();

((Ellipse) result).Fill = new SolidColorBrush(Colors.Yellow);

But my problem is that the XamlReader class is not available in Windows 8.1 phone runtime app. I am using Visual Studio 2013. I have found a namespace called Windows.UI.Xaml which is there in Windows 8.1 phone runtime app.

Can anyone please guide me on how to implement the functionality of loading new Xaml in Windows Phone 8.1 runtime.

1
Sadly, it seems that the WinRT runtime isn't able to load XAML dynamically. Being able to convert a xaml string into an object (and therefore executing potentially harmful stuff) is apparently considered as a breach in the WinRT "don't load dynamic code" policy...Eilistraee
@Eilistraee..So is there any other way to achieve this functionality....what I want to do is have a set of templates and change a particular region of my app depending on the template selected by userAvinashK
If it does not exist (yet ?) I would write my own parser. I mean you could do that (not overly complicated, just dynamically parse the XAML entity, its properties and attached properties, and its children) or else change the requirements.Max
According to the answer below, it seems to be available on 8.1. It wasn't on 8.It's Good news, I take note, and sorry for the first comment :)Eilistraee

1 Answers

3
votes

The XamlReader is available on both Windows Phone 8.1 Silverlight apps and Windows Phone 8.1 Store apps: