Using VS - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Using VS arrow Page 2 - Working With Avalon Today: Getting Started With XAML
Working With Avalon Today: Getting Started With XAML
By Nick Chase

Rate This Article: Add This Article To:

Working With Avalon Today: Getting Started With XAML - ' Getting Serious'
( Page 2 of 2 )

: Adding Code"> Getting Serious: Adding Code

Because this is just an introduction, I'm not going to build a complicated application. However, it's important to understand how the process of adding functionality to a XAML application works. We'll start by simply popping up a message box when the user clicks the window.

Ultimately, you should be able to embed inline code into a XAML document. At the time of this writing, Xamlon only supports code-behind classes, so that's how I handle it here.

ADVERTISEMENT

Start by creating a library that contains the method to use. In this case, you want a simple click event handler:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;

namespace XAMLTutorial
{
    public class Tutorial
    {
        public void ClickMe(object sender, EventArgs e){
           MessageBox.Show("Hello world!", "This is the title bar");
        }
    }
}

For those of you unfamiliar with programming in C#, I create a namespace called XAMLTutorial (similar to a package, for you Java programmers out there) and added a class called Tutorial. That class has a single method, ClickMe. You can call the method anything you like, but the structure of the arguments is important for later.

Compile the file with a reference to the Xamlon.dll, as in:

csc /t:library /reference:Xamlon.dll /out:.\tutorial.dll tutorialclass.cs

where tutorialclass.cs is the file you just saved. If you don't have a copy of Xamlon.dll in the same directory as the .cs file, make sure you reference it in its actual location.

Now it's time to reference the class from the XAML application:

<?xml version="1.0"?>
<?Mapping XmlNamespace="tutCode" ClrNamespace="XAMLTutorial" Assembly="tutorial"?>
<Window xmlns="http://schemas.microsoft.com/2003/xaml"
    Width="310" Height="285"
    xmlns:def="Definition"
    def:Class="XAMLTutorial.Tutorial" Click="ClickMe">
  <Canvas>
     <Rectangle RectangleWidth="296" RectangleHeight="252"
            Fill="Yellow" Stroke="Red"
            RectangleLeft="3" RectangleTop="3"
            StrokeThickness="5"
            RadiusX="30" RadiusY="20" />
...

The first step is to map the XML file to the actual code using the Mapping processing instruction. For the moment, the XmlNamespace is required, but arbitrary; we won't be using it. The important part of this processing instruction maps the actual programmatic namespace XAMLTutorial to the tutorial.dll file. Notice that I've left ".dll" out of the Assembly attribute. Also, if tutorial.dll is not in the same directory as your XAML file, make sure to specify the path.

Now you're ready to actually reference the class. First, create the Definition namespace, which typically uses an alias of def:. From there, assign the XAMLTutorial.Tutorial class to the Window object and specify that the Click event is to be handled by the ClickMe method.

Save the file and preview it, and then click the window. You should see an alert box, as in Figure 6.

That takes care of making something programmatic happen with the visual elements. Now let's look at making something programmatic happen to the visual elements.

Binding to Objects

Now you've got a nice looking window that's basically a glorified button. How can you really hook it in with some kind of application? The answer lies in binding the objects in the XAML window to the objects in your code.

To finish of this project, we'll create code that updates the text with the number of times the window's been clicked, and just to make it interesting, we'll save the information to a file so it's preserved between viewings of the document.

Start by adding the file reading and updating to the Tutorial class:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.IO;

namespace XAMLTutorial
{
    public class Tutorial
    {
        public void ClickMe(object sender, EventArgs e){
         MessageBox.Show(UpdatedCount(), 
         "This is the title bar");
      }

     public String UpdatedCount(){
        String previousValue = ReadFile();
        if (previousValue == "){ 
           previousValue = "0";
        }
        Int32 currentInt = System.Convert.ToInt32(previousValue) + 1;
        WriteFile(System.Convert.ToString(currentInt));
        return System.Convert.ToString(currentInt);
    }

     public String ReadFile(){
        FileStream file =
          new FileStream("counter.txt", 
          FileMode.OpenOrCreate, FileAccess.Read);
        StreamReader streamReader = new StreamReader(file);
        string contents = streamReader.ReadToEnd();
        streamReader.Close();
        file.Close();
        return contents;
     }

     public void WriteFile(String textToWrite){
        FileStream file =
          new FileStream("counter.txt", 
          FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter streamWriter = new StreamWriter(file);
        streamWriter.Write(textToWrite);
        streamWriter.Close();
        file.Close(); 
     } 
 }
}

Starting at the bottom and working our way up, the WriteFile() and ReadFile() methods are fairly straightforward. If the counter.txt file doesn't exist, either method will create it. The actual text consists of a single integer, so reading the entire file will be fine.

The UpdatedCount() method is where the action actually happens. It reads the file and if there was no data, sets the original count to 0. It then increments the value and writes it out to the file for next time before returning it.

You can see it in action by replacing the MessageBox text with the value returned by UpdatedCount(). Recompile the library and click the XAML window a few times to see the message value change, as in Figure 7.

Now you can finally wire that data up with the objects in the actual XAML window. To do that, use the Tutorial class to implement the System.Windows.Serialization.IpageConnector interface:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.IO;

namespace XAMLTutorial
{
    public class Tutorial: System.Windows.Serialization.IPageConnector
    {

       Window _mainWindow;
       Text _message;

       public void ClickMe(object sender, EventArgs e){
           this._message.AddText(UpdatedCount());
       }

...
       public bool Connect(string id, object target)
       {
          switch (id)
          {
          case "mainWindow":
              this._mainWindow = (Window) target;
              break;
          case "message":
              this._message = (Text) target;
              break;
          default:
              break;
          }
                   
          return false;
      }

   }
}

By implementing the IpageConnection interface, the system knows to compare the ID of any object in the document using the Connect() method, which associates the actual object with variables declared at the top of the class. This way, when the user clicks the window, instead of popping up an alert box, you can set the body of the Text object to the new value.

To make this work, assign ID attributes to the Window and Text elements. You might also want to move the text over to make it look a little nicer, and remove the initial Hello World text:

<?xml version="1.0"?>
<?Mapping XmlNamespace="tutCode" ClrNamespace="XAMLTutorial" Assembly="tutorial"?>
<Window xmlns="http://schemas.microsoft.com/2003/xaml"
    Width="310" Height="285"
    xmlns:def="Definition"
    def:Class="XAMLTutorial.Tutorial" Click="ClickMe"
    ID="mainWindow">
  <Canvas>
...
     <Text FontSize="36" ID="message" 
            Canvas.Left="120" Canvas.Top="175"></Text>

  </Canvas>

</Window>

Now add the handler for the Load event, and you're done:

...
       public void ClickMe(object sender, EventArgs e){
           this._message.AddText(UpdatedCount());
       }

       public void LoadMe(object sender, EventArgs e){
           this._message.AddText(ReadFile());
       }

       public String UpdatedCount(){
          String previousValue = ReadFile();
          if (previousValue == "){
...

Recompile the class, and then close the document and re-open it to see the changes.

Additional Resources

As you might imagine, I've just scraped a few snowflakes off the top of the iceberg that is XAML. For example, I haven't even touched the issue of including a Windows Form in a XAML document, or vice-versa. Part of that is due to limitations in what's available at the time of this writing, but as Avalon firms up, expect support to broaden.

For more information on using Xamlon (and some cool tips and ideas), check out the Knowledge Base at http://www.xamlon.com/kb/. You'll find the SDK documentation at http://www.xamlon.com/docs/index.html, but at the time of this writing it's useful mostly for finding out what's available, as opposed to seeing it in use. (It's also good for finding out whether the class you're using isn't working because it's not implemented yet.)

You can also find more complete documentation on Longhorn and Avalon at http://longhorn.msdn.microsoft.com/lhsdk/port_reference.aspx, and an at-a-glance view of the relevant XAML elements at http://longhorn.msdn.microsoft.com/lhsdk/port_ref_elements.aspx.



 
 
>>> More Using VS Articles          >>> More By Nick Chase
 



DevSource video
Devsource Video Series
Manipulating Society through Technology
Jeremy Bailenson, Director of the Virtual Human Interaction Lab at Stanford University, talks about virtual reality, avatars, Moore's law, how real world behaviors influence online reality, and societal manipulation through technology!
>> Play video
>> Read article
>> See all videos
DevLife Blog

Julia explores the Robotics Studio! (It's for more than you think.)

MSDev Blog

Messages for Bill Gates!

Make it Work
.NET makes runtime type checking a breeze. See what Peter has to say about it in this week's tips!
News
Microsoft Counts on App Support for Vista
Microsoft has taken pains to demonstrate that Windows Vista will have ample application support.
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.