15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

overview ❘ 729<br />

}<br />

}<br />

}<br />

var app = new Application();<br />

app.Run(w);<br />

code snippet CodeIntro/Program.cs<br />

A similar UI can be created by using XAML code. As before, a Window element is created that contains a<br />

Button element. The Window element has the Title attribute set in addition to its content.<br />

<br />

<br />

<br />

code snippet XAMLIntro/MainWindow.xaml<br />

Of course, the Application instance from before is missing. This can be defined with XAML as well. In<br />

the Application element, the StartupUri attribute is set, which links to the XAML file that contains the<br />

main window.<br />

<br />

<br />

<br />

<br />

code snippet XAMLIntro/App.xaml<br />

using Custom .neT Classes<br />

To use custom .<strong>NET</strong> classes within XAML code, only the .<strong>NET</strong> namespace needs to be declared within<br />

XAML, <strong>and</strong> an XML alias must be defined. To demonstrate this, a simple Person class with the FirstName<br />

<strong>and</strong> LastName properties is defined as shown.<br />

namespace Wrox.ProCSharp.XAML<br />

{<br />

public class Person<br />

{<br />

public string FirstName { get; set; }<br />

public string LastName { get; set; }<br />

}<br />

}<br />

public override string ToString()<br />

{<br />

return string.Format("{0} {1}", FirstName, LastName);<br />

}<br />

code snippet DemoLib/Person.cs<br />

In XAML, an XML namespace alias named local is defined that maps to the .<strong>NET</strong> namespace Wrox.<br />

ProCSharp.XAML. Now it’s possible to use all classes from this namespace with the alias. In the XAML code<br />

a ListBox is added that contains items of type Person. Using XAML attributes, the values of the properties<br />

FirstName <strong>and</strong> LastName are set. When you run the application, the output of the ToString() method is<br />

shown inside the ListBox.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!