How to use Xaml Code Generator

Please note, you can add new Xaml Template by clicking on Add New Item and select any of Xaml Component available in Xaml Templates.
  1. For WPF Projects
  2. For Non WPF Projects like Silverlight, ASP.NET
  3. CLR Objects
  4. Naming Children
  5. xc:Ref - Reference something in Code Behind
  6. xc:This - References this keyword

For Already existing xaml pages in Visual Studio

  1. Click on the File in Solution Explorer
  2. Open Property Browser (Press F4)
  3. Change Build Type to "None"
  4. Replace "MSBuild:Compile" to "XamlGenerator" in Custom Tools

For non WPF projects like Silverlight, ASP.NET etc

  1. Create a new file "Select xml from from the file list" and change the name to "MyClass.xaml"
  2. Do steps 1 to 4 mentioned above for "MyClass.xaml"
  3. Add a seperate "MyClass.xaml.cs" file by adding c# file type
  4. Add a constructor with single method "InitializeComponent" in MyClass.xaml.cs
  5. Add namespace markup and class markup in MyClass.xaml as shown in following examples
  6. Right click on xaml files and click on "Run Custom Tool"

Sample Xaml
<MyBaseClass 
    x:Class="YourNameSpace.MyClass"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns="clr-namespace:WebApplication1"
   ></MyBaseClass>

Samle Code Behind
namespace YourNameSpace{
   using System;

   public partial class MyClass : MyBaseClass {
  
      // constructor
      public MyClass(){
         InitializeComponent();
      }    
   }
}

Please note, it is necessary to add MyClass.xaml.cs and add a constructor with InitializeComponent method, otherwise your object hierarchy will not load.

CLR Objects are now Ready

Now Xaml code is converted to CLR objects, you can use them in your project easily without any hassles. The code generated is .Net 2.0 compliant, so code can be used in .Net 2.0 framework as well.

Naming of Child Objects

Every child object inside a parent container can have x:Name specified. If you specify x:Name attribute for your children, then code behind will generate a private typed field with the name, that can be accessed in code behind.

xc:Ref - Reference something in Code Behind

You can use markup extension xc:Ref to reference something in code behind at time of creation.
<Button
    Tag="{xc:Ref this.WindowProperties.Context}"
    />

xc:This - References this keyword

You may beed it preferrably when you want to refer "this" keyword in any of your binding.
<TextBlock
    Text="{Binding Context.Title, source={xc:This}}"
    />

Last edited Sep 28, 2010 at 5:43 PM by neurospeech, version 5

Comments

No comments yet.