Rob Relyea

xaml:Blog

3 Coding Styles for Avalon Applications

There are 3 coding styles developers could use to build Avalon applications:

1.      Code Only

2.      Code + Markup (Runtime use of XamlReader)

3.      Code + Markup (Markup compiled)***

 

*** - Microsoft Development tools will recommend this style.

  

Coding Style 1: Code Only Application

Any CLR compatible language can write a code only application.

 

Example in C#:

1) Create Program.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Markup;

using System.IO;

 

namespace CodingStyles

{

    public class CodeOnlyWindow : Window

    {

        [STAThread]

        static void Main(string[] args)

        {

            Application app = new Application();

            new CodeOnlyWindow().Show();

            app.Run();

        }

 

        Button button1;

 

        public CodeOnlyWindow()

        {

            StackPanel sp = new StackPanel();

            button1 = new Button();

            button1.Content = "Hello";

            sp.Children.Add(button1);

            button1.Click += new RoutedEventHandler(button1_Click);

            this.Content = sp;

            this.Width = this.Height = 285;

            this.Left = this.Top = 100;

            this.Text = "Code Only Window";

 

        }

        void button1_Click(object sender, RoutedEventArgs e)

        {

            button1.Content = "Clicked";

        }

 

    }

}

 

2) Compile that with the c# compiler like this:

csc /out:CodingStyle1.exe Program.cs /lib:c:\Program Files\Reference Assemblies\Microsoft\WinFx\v3.0 /r:PresentationFramework.dll;PresentationCore.dll;WindowsBase.dll;UIAutomationTypes.dll

 

3) Run CodingStyle1.exe

 

Coding Style 2: Code + Markup (Runtime use of Xaml Parser)

Some developers will want a code only application, but will still want to use some xaml.  These developers can call the parser to load xaml at runtime. 

Any CLR compatible language will be able to do this.

 

Example in C#:
1) Create Program.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Markup;

using System.IO;

 

namespace CodingStyles

{

    public class CodePlusRuntimeParsingWindow: Window

    {

        [STAThread]

        static void Main(string[] args)

        {

            Application app = new Application();

            new CodePlusRuntimeParsingWindow ().Show();

            app.Run();

        }

 

        Button button2;

 

 

        public CodePlusRuntimeParsingWindow()

        {

            //Load file1.xaml

            StreamReader sr = new StreamReader("file1.xaml");

            DependencyObject rootElement =

                XamlReader.Load(sr.BaseStream) as DependencyObject;

 

            //Find element with ID of Button2

            button2 = LogicalTreeHelper.FindLogicalNode(rootElement, "button2")

               as Button;

 

            //Wire up event

            button2.Click += new RoutedEventHandler(button2_Click);

 

            this.Content = rootElement;

            this.Text = "Code Plus Runtime Parsing Window";

        }

 

        void button2_Click(object sender, RoutedEventArgs e)

        {

            button2.Content = "Clicked";

        }

 

    }

}

 

2) Create File1.xaml

<StackPanel xmlns="http://schemas.microsoft.com/winfx/avalon/2005">

      <Button ID="button2">HelloButton>

StackPanel>

 

Compile that with the c# compiler like this:

3) csc /out:CodingStyle2.exe Program.cs /lib::\Program Files\Reference Assemblies\Microsoft\WinFx\v3.0 /r:PresentationFramework.dll;PresentationCore.dll;WindowsBase.dll;UIAutomationTypes.dll

 

4) Run CodingStyle2.exe  (it should work identically to CodingStyle1.exe)

 

 

Coding Style 3: Code + Markup (Markup compiled)

A subset of CLR compatible languages will support this mode.

A language must have a CodeDom provider and provide msbuild target files for their language.

 

Microsoft languages that meet this criteria today are C#, Visual Basic and J#.  (J# has a few blocking bugs in currently available CTPs though).

I'm aware of at least two other language vendors who will be able to match this level of support in the near future.

 

More details about MarkupCompilation are in a blog post I did last year:  

 

1) Use Visual Studio – File/New Project/Avalon Application – call it CodingStyle3

2) Change Window1.xaml to look like this

<Window x:Class="CodingStyle3.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

    Text="CodingStyle3"

    >

    <StackPanel>

            <Button Name="button1" Click="Button1_Click">HelloButton>

    StackPanel>

Window>

 

3) Change Window1.xaml.cs to look like this

using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Media;

using System.Windows.Shapes;

 

 

namespace CodingStyle3

{

    ///

    /// Interaction logic for Window1.xaml

    ///

 

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            button1.Content = "Clicked";

        }

 

    }

}

 

4) Build and Run the application in VS  (it should work identically to CodingStyle1.exe and CodingStyle2.exe)

 

Benefits of Coding Style 3: Markup Compilation

Markup compilation provides the following benefits:

·         Xaml code is used as the element tree definition language giving many tools (form designers, timeline editors, vector graphics editors, 3d modelers, etc…) the opportunity to collaborate. (this is a benefit for coding style 2 & 3)

·         ID Lookup is automatic.  Event handlers can refer to an element by ID instead of having to call LogicalTreeHelper.FindLogicalNode like CodingStyle2 does.

·         Event Wiring is automatic.  Coding style 1 & 2 both needed to attach an event handler to the click event of the button.

·         Xaml code is compiled into a binary form.  Loading via the binary form is faster than parsing xml at runtime.

 

 

[3/27/2006 - updated to make sure object model and markup is up to date for Feb 2006 CTP.]

Posted on Apr 27 2005, 04:35 PM by rrelyea
Filed under: ,
PostTypeIcon
21,401 Views

Comments

  • hacked.brain said:
    April 27, 2005 6:18 PM
  • hacked.brain said:
    April 27, 2005 7:37 PM
  • Kevin Daly said:
    Thanks for that.

    One case where someone might want to use Coding Style 2) would be if markup was to be the result of an XSLT transformation. Admittedly features built into Avalon and (including converters and advanced databinding) remove a lot of the cases for doing that, but it's nice to have the option nevertheless (actually I think I just have a soft spot for XSLT).
    April 27, 2005 8:06 PM
  • rrelyea said:
    Sure...You can parse XAML at runtime a few ways.
    1) Call Parser.LoadXml directly, passing in a stream.
    2) Navigate to a .xaml file on the webserver where the app came from.
    3) Navigate to a .xaml file (that you have marked as a "Resource" not a "Page" in the project file build action).

    XSLT could be performed:
    1) at runtime, as Kevin suggested.
    2) at buildtime in msbuild. you would need a task that takes an input, runs an xslt on it, and outputs a xaml "Page".

    People should work to understand indigo & databinding technologies in Avalon to see if that is a better solution for their task than xslt at runtime.

    Navigating to the result of an XSLT transform is not a great experience for users. Good applications don't require a navigation to occur just because the client application needs data from the server.
    Thx, Rob
    April 28, 2005 11:06 AM
  • Rob Relyea said:
    Nish is starting to use WPF with C++.He posts about using C++ and XamlReader.Load together.
    There are...
    March 26, 2006 10:41 PM
  • Rob Relyea said:
    Tim Anderson asked a question on the MSDN forum for WPF.

    &amp;nbsp;I'm not 100% clear about the relationship...
    March 28, 2006 8:51 AM
  • I received a customer request for how a XAML downloaded from a server can still have events. Let’s discuss

    June 3, 2009 11:44 PM
  • 3 Coding Styles for Avalon Applications - Rob Relyea

    September 17, 2014 1:19 PM