I like to think of XAML as an “object instantiation script”. According the to the main books on the subject it should be possible to utilise XAML to create any kind of .net object.
Practical examples include WWF (Windows Workflow Foundation) , which allows the storage of definition in XAML, which is nothing to do WPF. WPF (Windows Presentation Foundation) was the original reason XAML was created, but XAML was designed to be independent.
So I was thinking, why not see if I can define a traditional “Winform” in XAML. Why would I want to? I thought it might be fun. As it turns out, it may actually be useful in some scenarios. (With a great stretch of the imagination)
So does it work? Oh yes it works and it works well. “Well” means that VS2008 provides full intellisense for tags within the Xaml designer, as well as “code behind”. Now that, my friends, is cool. Imagine being able to create form layouts using XML tags instead of that oh-so-last year winforms designer! The result is surprisingly WPF like, which I find intriguing.
To create the example below, I created a WPF project, then removed the default WPF “Window1.xaml” and replaced it with my own “Form1.xaml”:
<Form Name="Form1" x:Class="Form1" Text="Hello"
<TextBox Name="txtName" x:Name="txtName" />
<Button Name="cmdSayHello" Text="Say Hello" Click="Button_Click" />
Please note that features such as code behind (partial classes), event hooks and most things in the “x” namespace work fine.
Creating XAML from an existing Winform
For even more fun and games, you can feed a running instance of a Winform into XAML Writer and get XAML source. Sadly winforms incorporates read-only properties, so without massaging the Xml you’re not going to be able to clone a Winform using XAML serialization just yet.
The code would look something like this:
Dim loWinform As Form = Me ' Some Winform
Dim lsWinformXaml As String = XamlWriter.Save(loWinForm)
Dim loClonedForm As Form = XamlReader.Load(new XmlTextReader(new StringReader(xaml)))
See this Mike Hillberg’s object cloning article for more information.
So where from here?
What’s the use of it? Well for me it proved that Xaml can be used to create any sort of object graph.
Possible uses for this:
- Embedding Winforms instantiation code within a WPF XAML document (something I haven’t tried)
- Streaming Winforms form definitions from a server down to a client (effectively allowing a WebServer to render Winforms just like it renders HTML pages)
- Providing a good interim step in creating a Winforms to WPF Converter
If you find this topic interesting, ask questions or download a sample project, write some comments on the blog. If I can see interest in the topic I may develop it further.
|Share this post :|