Volunteer .NET Evangelist

A well oiled machine can’t run efficiently, if you grease it with water.
posts - 44, comments - 88, trackbacks - 2, articles - 0
  首页  :: 联系 :: 订阅 订阅  :: 管理

XamlReader.Load(): Build Up Your Own XamlPad

Posted on 2006-02-21 19:49  Sheva  阅读(...)  评论(...编辑  收藏
    If you have been dabbling with any CTP release of WINFX SDK, you probably have been irritated by the unstability of the XamlPad.exe which is shipped with the SDK. the XamlPad.exe crashes regularly on my machine because of some unhandled peculiar exceptions. so I have long been planning to build up my own XamlPad.
    When I first encounter the XamlReader class which is in the System.Windows.Serialization namespace, I begin to realize that this class and the powerful methods it provides can serve me pretty well in designing my own XamPad, the trick here is that the XamlReader class has a method called Load which can take some arbitrary well formed XAML text as input, and produces corresponding WPF control as output, the signature of this method is:

public static Object Load (XmlReader reader)

    So first off, you have to construct an XmlReader object based on the XAML text input, and pass it to the XamlReader.Load method as an argument:

            StringReader stringReader = null;
            XmlTextReader xmlReader 
= null;
= new StringReader(xamlDocument);
= new XmlTextReader(stringReader);
                UIElement documentRoot 
= (UIElement)XamlReader.Load(xmlReader);
= documentRoot;
catch (Exception ex)
                TextFlow errorText 
= new TextFlow();
                Paragraph p 
= new Paragraph();
= new FontFamily("Segoe UI");
= Brushes.Red;
= ex.Message;
= HorizontalAlignment.Center;
= errorText;
if (stringReader != null) stringReader.Close();

if (xmlReader != null) xmlReader.Close();

    Note that when an exception is throw in this process, the exception message will be printed out in the executionPad which is the container for the UIElement constructed from XAML input. the following is the sreenshot of this little helpful application:

XamlPad in Execution View:

XamlPad in Xaml View:

For the complete source code,please check here.