แสดงบทความที่มีป้ายกำกับ Silverlight แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Silverlight แสดงบทความทั้งหมด

วันจันทร์ที่ 10 กันยายน พ.ศ. 2555

Sort Data Using Code with the Silverlight CollectionViewSource

Sort Data Using Code with the Silverlight CollectionViewSource

As a follow-up to last week's blog posting and newsletter, this week I am going to show you how to use the CollectionViewSource object in Silverlight to sort data using code. Sometimes you need something a little more flexible, so you will need to resort to writing some code. You can take advantage of the CollectionViewSource from your XAML, but dynamically change the sort order of your lists with just a few lines of code.
For this example, I will be using a simple Product class with three properties, and a collection of Product objects using the Generic List class. Try this out by creating a Product class as shown in the following code:
public class Product
{
public Product(int id, string name, string type)
{
ProductId = id;
ProductName = name;
ProductType = type;
}
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductType { get; set; }
}
Create a collection class that initializes a property called DataCollection with some sample data as shown in the code below:
public class Products : List<Product>
{
public Products()
{
InitCollection();
}
public List<Product> DataCollection { get; set; }
List<Product> InitCollection()
{
DataCollection = new List<Product>();
DataCollection.Add(new Product(3, "PDSA Framework", "Product"));
DataCollection.Add(new Product(1, "Haystack", "Product"));
DataCollection.Add(new Product(2, "Fundamentals of .NET eBook", "Book"));
return DataCollection;
}
}
The screen shot shown in Figure 1 is a Silverlight page that allows the user to sort the Product data by either the Product Name or the Product Type.
Sort Data Using Code
Figure 1: Sorting data using code in Silverlight
Notice that the data added to the collection is not in any particular order. Create a Silverlight page and add two XML namespaces to the UserControl.
xmlns:scm="clr-namespace:System.ComponentModel;assembly=System.Windows"
xmlns:local="clr-namespace:SLSortData"
The 'local' namespace is the name of the project that you created. The 'scm' namespace references the System.Windows.dll and is needed for the SortDescription class that you will use for sorting the data. Create a UserControl.Resources section in your Silverlight page that looks like the following:
<UserControl.Resources>
<local:Products x:Key="products" />
<CollectionViewSource x:Key="prodCollection"
Source="{Binding Source={StaticResource products},
Path=DataCollection}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ProductName"
Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
The first line of code in the resources section creates an instance of your Products class. The constructor of the Products class calls the InitCollection method which creates three Product objects and adds them to the DataCollection property of the Products class. Once the Products object is instantiated you now add a CollectionViewSource object in XAML using the Products object as the source of the data to this collection. A CollectionViewSource has a SortDescriptions collection that allows you to specify a set of SortDescription objects. Each object can set a PropertyName and a Direction property. As you see in the above code you set the PropertyName equal to the ProductName property of the Product object and tell it to sort in an Ascending direction.
The two Radio Buttons on the page are created using the following xaml:
<RadioButton Name="rdoSortName"
Tag="ProductName"
Checked="SortTheData"
Content="Sort by Name" />
<RadioButton Name="rdoSortType"
Tag="ProductType"
Checked="SortTheData"
Content="Sort by Type" />
Notice the Tag attribute has been set with the name of the property that you want to sort on. The Checked attribute is set to an event procedure called SortTheData. This event procedure is shown in the following code.
private void SortTheData(object sender, RoutedEventArgs e)
{
if (lstData != null)
{
ICollectionView dataView;
dataView = (ICollectionView)lstData.ItemsSource;
dataView.SortDescriptions.Clear();
dataView.SortDescriptions.Add(
new SortDescription(((RadioButton)sender).Tag.ToString(),
ListSortDirection.Ascending));
lstData.ItemsSource = dataView;
}
}
In this code you are retrieving the CollectionViewSource data from the ItemsSource property of the list box. You cast this as a ICollectionView object. Clear any existing SortDescriptions and then add a new SortDescription object to the SortDescriptions collection on the CollectionView. You pass to the constructor of the SortDescription class the Tag property of the Radio button that was selected. Remember this is the name of the property that you wish to sort on. The second parameter passed to the constructor is the direction of the sort, either Ascending or Descending.
That's all there is to it. A simple way to allow your users to sort on different properties with just a few lines of code!
NOTE: You can download the complete sample code (in both VB and C#) at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Sort Data Using Silverlight CollectionViewSource" from the drop-down.
 
 

วันจันทร์ที่ 9 กรกฎาคม พ.ศ. 2555

Expand/collapse Group when click on group header

Expand/collapse Group when click on group header

When I have a grid that groups items is there a way to expand/collapse the group when the user clicks on the text in the header? Right now the only way to expand/collapse a group is to click on the expand button in the header.

To accomplish your task handle the MouseLeftButtonUp event in the following manner:

[C#]Open in popup window
private void tableView1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {            
TableView view = sender as TableView;            
TableViewHitInfo hi = view.CalcHitInfo(e.OriginalSource as DependencyObject);            
if (hi.HitTest == TableViewHitTest.GroupValue)                
ToggleExpandedState(view);        
}        

private void ToggleExpandedState(TableView view)        
{            
if (view.Grid.IsGroupRowExpanded(view.FocusedRowHandle))                
view.CollapseFocusedRow();            
else view.ExpandFocusedRow();        
}

วันศุกร์ที่ 22 มิถุนายน พ.ศ. 2555

Silverlight Set IE Full Screen

public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ToggleFullScreen();
        }
 
        private void ToggleFullScreen()
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }
    }

วันอาทิตย์ที่ 17 มิถุนายน พ.ศ. 2555

How to sort combind field in datagrid.

I use the code below to combine

<sdk:DataGridTemplateColumn Header="MergeColumn" Width="90">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="3,4,0,0">
<TextBlock Text="{Binding FieldA}" />
<TextBlock Text="{Binding FieldB}" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>

วันพฤหัสบดีที่ 7 มิถุนายน พ.ศ. 2555

Xap packaging failed. Object reference not set to an instance of an object

I'm getting this error message on my PC when I try to build  Silverlight App:
Xap packaging failed. Object reference not set to an instance of an object 
I'm using Dropbox. On my laptop, It works perfectly fine and I can debug etc...

Please tried many things such as:
  • Delete obj/Debug Folder
  • Check for files which are missing on the Solution Explorer

วันพุธที่ 16 พฤษภาคม พ.ศ. 2555

Photo Gallery Wall

An attractive image gallery containing 16 images. Images and their captions (if configured) can be viewed by clicking. If no images are selected, the gallery will automatically switch to slideshow mode after 10 seconds. Includes a how-to document that provides an overview of the creation process using Blend and detailed description of functionality! View Download (706K ZIP)

Create image gallery,store picture in SQL Server 2005 Express

How do the user add picture?
I have an example here like using Upload
C#
private void Btn_AddAtt_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog d = new OpenFileDialog();
d.Filter = "Image (*.jpg, *.png)|*.jpg;*.png";
d.Multiselect = true;
if (d.ShowDialog() == true)
{
foreach (FileDialogFileInfo f in d.SelectedFiles)
{
Stream s = f.OpenRead();
byte[] fileBytes = new byte[s.Length];
int byteCount = s.Read(fileBytes, 0, (int)s.Length);
string fileContent = Convert.ToBase64String(fileBytes);
s.Close();
//Upload here
// mydata.UploadFileAsync(f.Name, fileContent);
}
}
}
mydata.LoadImage_Completed(....)
{
byte[] m;
Stream b;
if (e.Error == null)
{
List<ImageFile> k = e.Result as List<ImageFile>;
//using for-looping with int i to get the content and change it back to Image
m = Convert.FromBase64String(k[ i].Content);
b.WriteByte(m);
BitmapImage k = new BitmapImage();
k.SetSource(b);
Image mypic = new Image();
mypic.Source = k;
LayoutRoot.Children.Add(mypic);
}
}
In the WCF
public void UploadFile(string fileName, string text)
{
//you have now the text with Base64 Configuration, you can insert it into your SQL database
// next time you can get it back by loadImage
}
public class ImageFile
{
public string Name { get; set; }
public string Content { get; set; }
}
public string LoadImage()
{
//you can now find all the Row in the Database and send back the Name and Text
//you may return List<ImageFile>
}
I didnt try them all in VS but the upload part should work very well

Silverlight Tip How to Dynamically Load and Display Images

How to Dynamically Load and Display Images

Loading images in Silverlight is fairly straight forward. The first step is to create what’s called a Uniform Resource Identifier (URI). The URI is essentially a string that points to a resource. The resource can be locally in the project or out on the Internet. Images that are loaded locally must be first added to your Visual Studio project.

Image image = new Image();
Uri uri = new Uri("images/myImage.png", UriKind.Relative);
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
image.SetValue(Image.SourceProperty, img)
Now, to display the image you will need to add it to the Children of an element that you have declared in your XAML. For example, let’s say you have created a Canvas object in your Page.xaml under the parent Grid object. Using the x:Name tag, give it the name “Map”:
<Grid x:Name="MainGrid">
  <Canvas x:Name="Map">
   </Canvas>
</Grid>
Now, back in your Page.xaml.cs file you can dynamically add the image you just created to the canvas object like this:
Map.Children.Add(image);
Btw, declaring an image in your XAML works the same way. Example:
<Image Source="images/MyImage.png"></Image>

Silverlight Hardware Acceleration

Silverlight Hardware Acceleration

           
Caching visual elements as bitmaps allows you to take advantage of hardware acceleration. Once an object or tree of objects has been cached as a bitmap, it no longer goes through the render phase as the application refreshes, rather, the cached bitmap is rendered. The cached bitmap swapping is able to take advantage of hardware acceleration from the user’s GPU which can yield significant performance improvements for some scenarios.
Shows how caching can improve performance.Hardware acceleration can benefit performance for the following scenarios:
  • Blending two static layers using opacity. For example, you can mark both trees of objects as cached, and the opacity animation will be executed using Hardware Acceleration.
  • Transforming objects (e.g. stretching and rotating).
NoteNote:
Caching objects can hurt performance if you misuse it. See How Hardware Acceleration Works below.
In order to cache objects and allow them to take advantage of hardware acceleration, do the following:
1. Enable composition caching at the plug-in level by setting the EnableGPUAcceleration parameter to "true".
<param name="EnableGPUAcceleration" value="true" />
2. You can now enable GPU acceleration on the element(s) you wish to cache by specifying a CacheMode value of BitmapCache on the object or container of objects.
<StackPanel CacheMode="BitmapCache" … />
You can cache a single UIElement or, as in the StackPanel example above, a container UIElement and all of its children.
The illustration below summarizes how Hardware Acceleration works.
Diagram showing hardware accleration process.
Notice that not everything can be hardware accelerated. Effects like DropShadowEffect and OpacityMask can only be rendered by the software. Also, WriteableBitmap goes through its own rendering pipeline and therefore cannot take advantage of hardware acceleration.
When you cache an object, you are creating multiple rendering surfaces in the VRAM which are then accelerated using the GPU. Other visible objects in your application that are not cached are rendered as surfaces in software. Your performance will be best if you can minimize the total number of rendering surfaces and get the hardware to do work where it can. Note that BitmapCache is the only supported cache-mode.

How to Silverlight application close browser?

What do you mean by "terminate the application"? Do you want to close your browser window or you want to take the user to another page outside of your silverlight application?
If you want to close the browser window, put the following code to the button click event handler:

HtmlPage.Window.Invoke("CloseWindow");

and put a CloseWindow javascript function on your page:

function CloseWindow()
{
window.close();
}

If you want to take the user to another page:
HtmlPage.Window.Navigate(new Uri("SomeUrl));

If you are developing a secured site and want to close the browser window just after the user logout from the application, this small tip will help you. This is not a difficult job to implement. Just a single line of code will do the trick for you.

Use "System.Windows.Browser.HtmlPage.Window.Invoke()" method to call the Close() method of the browser window as shown in the below code snippet:
 
private void OnCloseClick(object sender, RoutedEventArgs e)
{
    System.Windows.Browser.HtmlPage.Window.Invoke("close");
}


The above code when called will close the browser window where your Silverlight application is hosted. If it is a tab, it will close the Window tab instead. If you are using it inside the Internet Explorer, it will confirm you whether you really want to close the browser. If you press "No", it will remain in that page and clicking "Yes" will close the browser tab/window.

SNAGHTMLfcd46a3

วันพฤหัสบดีที่ 10 พฤษภาคม พ.ศ. 2555

Microsoft เริ่มให้น้ำหนักกับ HTML5 มากกว่า Silverlight ของตนเอง ?

มีข่าวออกมามากมายเกี่ยวกับ Microsoft ว่า กำลังจะให้น้ำหนักกับ HTML5 มากกว่าเทคโนโลยี Silverlight ของตนเอง

ในการสัมมนา Professional Developers Conference (PDC) ของ Microsoft ที่ผ่านมา Microsoft พูดถึงการรองรับ และการสนับสนุน HTML5 ในซอล์ฟแวร์ Microsoft มากขึ้นเรื่อยๆ แต่พูดถึง Silverlight ของตนเองน้อยมาก

นาย Bob Muglia ผู้บริหารของ Microsoft ดูแลด้าน server and tools business กล่าวว่า “Silverlight จะยังคงพัฒนาอย่างต่อเนื่อง เพื่อให้งานได้กับหลากหลาย OS และ browser โดยเฉพาะบน Windows Phone .. แต่ HTML5 จะเป็นมาตรฐานการทำงานข้าม platform ที่แท้จริง รวมทั้งบนระบบปฏิบัติการ iOS ของ Apple ด้วย”
อย่างไรก็ตาม หลังสัมมนา เขาก็ได้ออกมาย้ำว่า Microsoft จะยังพัฒนา Silverlight อย่างต่อเนื่องบน Windows Phone และอุปกรณ์อื่นๆ เพียงแต่มองว่า HTML5 จะรองรับการทำงานข้ามเครื่องได้กว้างกว่าในอนาคต

นอกจากนี้ นาย Dean Hachmovitch ผู้จัดการของฝ่าย Internet Explorer ของบริษัท Microsoft ได้พูดอย่างชัดเจนว่า “เว็บในอนาคต คือ HTML5”
มาตรฐาน HTML5 นั้น ได้ถูกเริ่มต้นผลักดันอย่างมาก โดย Apple ในช่วงต้นปีนี้ 2010 หลังจากที่ออกจำหน่ายเครื่อง iPad และ iPhone ที่นำเทคโนโลยี HTML5 มาใช้งานแทน Adobe Flash และ Steve Jobs ก็เคยพูดว่า “Flash กำลังจะตาย HTML5 จะเป็นอนาคต”

การใช้งานอินเตอร์เน๊ตต่อไป จะมีมากกว่าแค่ตัวหนังสือ แต่จะมีภาพเคลื่อนไหว วิดีโอ เสียง, การใช้งานข้าม platform, การทำงานผ่านมือถือมากขึ้น ดังนั้น มาตรฐานในการรองรับสื่อเหล่านี้เป็นสิ่งที่จำเป็นและสำคัญ

แต่อย่างไรก็ดี HTML5 ยังเป็นแค่ มาตรฐานฉบับร่าง ในองค์กร World Wide Web Consortium (W3C) และกำลังถูกร่างให้เป็น มาตราฐานในการแสดงผลหน้าเว็บไซด์ โดยเฉพาะการเล่นภาพเคลื่อนไหว และวิดีโอ, หรือ การรองรับการทำงาน drag-and-drop, หรือการรองรับ การ Plug-in จากผู้ผลิตรายอื่นๆ อย่างเช่น Silverlight ของ Microsoft หรือ Flash ของ Adobe ด้วย

แม้ว่า HTML5 กำลังค่อยๆ ถูกยอมรับ และเริ่มเข้ามาเป็นมาตรฐานมากขึ้นเรื่อยๆ แต่แน่นอนว่า Adobe Flash และ Microsoft Silverlight จะยังคงไม่ถูกตัดทิ้งไปในระยะอันใกล้นี้แน่ เพราะยังมีเว็บไซด์ และโปรแกรมอีกจำนวนมาก ที่ถูกเขียนมาให้ใช้กับ Flash หรือ Silverlight และการเปลี่ยนเขียนขึ้นใหม่ เพื่อไปใช้ HTML5 ก็คงต้องใช้เวลาอีกพอสมควรทีเดียว
ดูเหมือนทั้ง Apple และ Microsoft เริ่มให้น้ำหนักไปที่ HTML5 มากขึ้นเรื่อยๆ นะ

เนื่องจากโปรแกรม Flash และ Silverlight ไม่ได้รับการสนับสนุนในอุปกรณ์ Mobile เท่าที่ควรและในบางประเทศที่ระบบเครื่องข่ายยังเป็น 2.5G ก็ไม่เหมาะที่จะใช้งาน แต่หากเป็น Intranet ในองค์กรที่มี LAN 10MB/100MB ก็สามารถทำได้ดี แต่หากเมื่อไรระบบเครื่อข่าย 3G มีการใช้อย่างแพร่หลายและทั่วถึงจะมีการใช้งาน Flash and Silverlight เพิ่มขึ้น

Rich Internet Application (RIA)

ปัจจุบันการเว็บแอพพลิเคชั่น (Web Application) ได้มีการพัฒนาอย่างแพร่หลายและเป็นไปอย่างรวดเร็ว อีกทั้งขีดความสามารถและความสวยงาม รวมถึงฟังก์ชันต่างๆ ที่ช่วยเพิ่มความสะดวกสบายในการใช้งานก็มีเพิ่มขึ้นเป็นอย่างมาก โดยส่วนมากแล้วเว็บแอพพลิเคชั่นจะถูกใช้กับงานที่มีความซับซ้อนไม่มากนัก ซึ่งพบเห็นได้ทั่วไป เช่น กระดานสนทนา (web board) เว็บไซต์พาณิชย์อิเล็กทรอนิคส์ (E-commerce) เว็บเมล์ (web-based email / webmail) เว็บบล็อก (Weblog) เป็นต้น และในขณะเดียวกันก็มีเว็บแอพพลิเคชั่นอีกประเภทหนึ่งที่เรียกว่า Rich Internet Application (RIA) เกิดขึ้นและกำลังมีจำนวนเพิ่มมากขึ้นอย่างต่อเนื่อง
ซึ่ง RIA ก็คือแนวคิดใหม่ของเทคโนโลยีที่ถูกพัฒนาขึ้นบนเว็บ โดยเกิดจากการผสมผสานองค์ความรู้และเทคโนโลยีการพัฒนาเว็บในยุคใหม่เข้าด้วยกัน ทำให้ผู้ใช้สามารถเข้าถึงและใช้งานเว็บไซต์ได้เหมือนกับการใช้งานโปรแกรมบนคอมพิวเตอร์ เช่น ผู้ใช้สามารถ drag and drop อ็อบเจ็คต่างๆภายในเว็บไซต์ได้เช่นเดียวกับโปรแกรมบนคอมพิวเตอร์ เป็นต้น RIA จึงเป็นเหมือนเทคโนโลยีที่ทำให้เว็บไซต์เข้าใกล้ผู้ใช้มากขึ้น ยืดหยุ่นมากกว่าเดิม และมีลูกเล่นและฟังก์ชันใหม่ๆ ที่ทำให้การเล่นอินเตอร์เน็ตและการเข้าถึงเว็บไซต์มีประโยชน์มากขึ้น เพลิดเพลินมากขึ้นอีกด้วย ตัวอย่างของเทคโนโลยี RIA หลักๆ ที่เป็นที่นิยมและเปิดให้นักพัฒนาสามารถนำไปใช้ได้ เช่น Microsoft Silverlight, Adobe Flash/Flex/AIR, JAVAFX, Google Gears
จากจุดเด่นของแนวคิด RIA ที่ได้กล่าวถึงข้างต้น ซึ่งเป็นส่วนหนึ่งในความสามารถของ Microsoft Silverlight ประกอบกับความสามารถในส่วนของการสร้างส่วนติดต่อผู้ใช้ (User Interface) ที่มีความสวยงาม หรูหรา รวมไปถึงความสามารถทางด้านมัลติมีเดีย เช่น สามารถแสดงผลวีดีโอที่มีคุณภาพระดับ High Definition (HD) ได้ สามารถทำงานกับไฟล์เสียง ในระดับ CD Quality ที่ 64 กิโลไบต์ต่อวินาที, Radio ที่ 32 กิโลไบต์ต่อวินาที และ HD Video Content ที่ 2 เมกะไบต์ต่อวินาที และสามารถทำ Video Streaming ได้ดีกว่าแพลตฟอร์มอื่นและสามารถทำงานที่ค่อนข้างซับซ้อนได้ดี จึงทำให้ Microsoft Silverlight เป็นเทคโนโลยีที่น่าสนใจ แต่กลับมีผู้ที่รู้จักและสามารถใช้งาน Microsoft Silverlight ได้ไม่มากนักในประเทศไทย ทางผู้จัดทำซึ่งได้เล็งเห็นข้อดีดังกล่าวข้างต้นของ Microsoft Silverlight จึงอยากจัดทำสื่อการสอนการใช้ Microsoft Silverlight เบื้องต้น เพื่อเป็นการเผยแพร่ความรู้เกี่ยวกับ Microsoft Silverlight แก่บุคคลทั่วไปและผู้ที่สนใจให้สามารถนำความรู้ไปต่อยอดได้

รู้จักกับ Silverlight

รู้จักกับ Silverlight

ช่วงนี้กระแส Rich Internet Application กำลังแรง เพราะค่ายซอฟต์แวร์ใหญ่ๆ ต่างทยอยเปิดตัวโซลูชันของตัวเอง Silverlight เป็นของค่ายไมโครซอฟท์

Silverlight
หลังจากการเปิดตัวอย่างเป็นทางการโดย Scott Guthrie (General Manager, Microsoft Developer Platform) ในช่วง Keynote ในงาน MIX 07 ที่ลาสเวกัสเมื่อต้นเดือนที่ผ่านมา Silverlight ก็ถูกพูดถึงในวงกว้างจากทั้ง Bloggers และเว็บไซต์ต่างๆ ที่มีชื่อเสียง ว่าจะเป็นนวัตกรรมใหม่ที่มาตอบสนองความต้องการทางด้าน Rich Internet Application (RIA) ผ่านเบราว์เซอร์ได้อย่างน่าตื่นตาตื่นใจ ผมได้รับคำเชิญชวนจากคุณ mk ให้ช่วยเขียนถึงเจ้าเทคโนโลยี Silverlight จากไมโครซอฟท์นี้สักหน่อย ก็เลยถือว่าเป็นโอกาสอันดีที่จะได้แนะนำให้นักพัฒนาหลายๆ ท่านที่สนใจได้รู้จัก Silverlight มากขึ้นครับ

Silverlight คืออะไร?

โดยนิยาม Silverlight คือ ดอทเน็ตปลั๊กอินที่ช่วยให้นักออกแบบ และนักพัฒนาสามารถพัฒนาแอพพลิเคชั่นประเภทมัลติมีเดียสมบูรณ์แบบสำหรับเบราว์เซอร์ได้ในหลายๆ เบราว์เซอร์ และสามารถรันได้บนหลายแพลตฟอร์ม นั่นหมายถึงว่า เราสามารถรันแอพพลิเคชั่นที่ทำด้วย Silverlight ได้ทั้งบน Firefox, Safari และที่แน่นอนก็คือ IE นอกจากนี้มันยังสามารถรันได้ทั้งบนวินโดว์สและแมคอินทอชอีกด้วย
Silverlight จะมีขนาดใหญ่เต็มที่ไม่เกิน 4 MB (ในปัจจุบันอยู่ที่ราว 1.38 MB) ซึ่งสามารถดาวน์โหลดได้ภายในราว 20 วินาทีด้วยอินเทอร์เน็ตความเร็วสูง โดยเราสามารถดาวน์โหลดได้ฟรีจากเว็บ http://www.silverlight.net หรือนักพัฒนาอาจฝังโค้ดมากับแอพพลิเคชั่นที่สร้างได้เช่นเดียวกันกับ Adobe Flash ซึ่งโดยทั่วไปหลังจากการติดตั้งก็จะสามารถรันแอพพลิเคชั่นด้วย Silverlight ได้ทันทีโดยไม่การสะดุดให้เสียอารมณ์ครับ
Silverlight 1.0 จะเริ่มเปิดให้ดาวน์โหลดได้อย่างเป็นทางการในช่วงฤดูร้อนของอเมริกา แต่ในตอนนี้เรามีถึงเวอร์ชั่น 5 ให้ใช้กันแล้ว

ฟีเจอร์สำคัญในเวอร์ชั่น 1.0 Beta

ในเวอร์ชั่นนี้ เราเน้นไปที่การใช้งานมัลติมีเดียบนอินเทอร์เน็ตค่อนข้างมาก ดังนั้นฟีเจอร์ที่สำคัญๆ ก็มีอาทิ
  • มี Built-in Codec ที่สนับสนุนการเล่นไฟล์วิดีโอแบบ VC-1, WMV และไฟล์เสียงแบบ MP3 และ WMA ภายในเบราว์เซอร์ เจ้า VC-1 Codec นี้เป็นก้าวกระโดดสำคัญในการยกระดับประสบการณ์มัลติมีเดียบนเว็บ เพราะสามารถทำให้เล่นไฟล์วิดีโอได้ในระดับความละเอียดเทียบเท่า HD DVD หรือ Blu-ray DVD เลยทีเดียว และเจ้า Codec ที่ว่านี้ยังถูกใช้แพร่หลายอยู่แล้วทั่วไป ไม่ว่าจะเป็นในอุปกรณ์พกพาต่างๆ, XBOX 360, Windows Media Player และ Windows Media Center ต่างๆ ทำให้สามารถนำไฟล์วิดีโอที่มีอยู่แล้วมาใช้กับ Silverlight ได้ทันที นอกจากนี้ยังสามารถเล่นมีเดียเหล่านี้บนเบราว์เซอร์ส่วนใหญ่ได้โดยไม่ต้องลงซอฟต์แวร์ใดๆ เพิ่มเติมอีกด้วยครับ
  • นอกจากจะสนับสนุนการเล่นไฟล์วิดีโอแล้ว หากใช้ควบคู่กับ Windows Media Server (ที่มีมากับ Windows Server ทั้งหลาย) ก็จะสามารถเล่นไฟล์วิดีโอที่เป็น Streaming ได้อีกด้วย ซึ่งจะทำได้ทั้งการเล่นและค้นหาไปยังตำแหน่งที่ต้องการ ช่วยให้ประหยัดแบนด์วิธของทั้งผู้ให้บริการและผู้ใช้
  • ช่วยให้ผู้ใช้สามารถสร้างส่วนติดต่อผู้ใช้ (User Interface) และอนิเมชั่นได้อย่างอิสระ แล้วยังสามารถเชื่อมต่อกับจาวาสคริปต์เพื่อตอบสนองต่อการกระทำของผู้ใช้ได้ดีแถมยังง่ายอีกด้วย ยกตัวอย่างเช่น เราอาจจะสร้างหน้าตัวเล่นวิดีโอด้วย XAML แล้วกำหนดชื่อให้กับมัน จากนั้นสั่งให้มันทำงานต่างๆ เช่น เล่น, หยุดเล่น หรือหยุดภาพ ได้จากจาวาสคริปต์ เป็นต้น
  • อนิเมชั่นเป็นแบบ Time-based ซึ่งเป็นแบบเดียวกันกับใน WPF ทำให้ความคลาดเคลื่อนของเวลาในการแสดงผลต่ำกว่าแบบ Frame-based ใน Adobe Flash อนิเมชั่นจะปรากฏตามเวลาที่เรากำหนดไว้อย่างแม่นยำ
  • นอกจากนี้เรายังสามารถใช้พื้นที่แบบ Full Screen ได้ โดยการขยายเป็น Full Screen นี้ไม่ใช่แค่การขยายวินโดว์สแบบเต็มจอ แต่เป็น Native Full Screen จริงๆ โดยที่เราสามารถควบคุมอินเทอร์เฟสได้อย่างอิสระ เช่น สามารถทำเมนูที่เป็น Overlay ลอยอยู่บนวิดีโอที่กำลังเล่นได้ เป็นต้น และในขณะที่ทำการย่อหรือขยาย วิดีโอก็จะย่อหรือขยายตามในขณะที่กำลังเล่นภาพอยู่โดยไม่สะดุด และไม่ต้องเล่นใหม่ทุกครั้ง
ประทับใจกันบ้างหรือเปล่าครับ ถ้าคิดว่าแค่นี้พอแล้ว เราลองมาดูฟีเจอร์เด็ดๆ ในเวอร์ชั่น 1.1 Alpha ที่ออกมาพร้อมกันต่อด้วยดีไหมครับ เผื่อจะมีอะไรเด็ดๆ กว่าเดิม

ฟีเจอร์สำคัญในเวอร์ชั่น 1.1 Alpha

แน่นอนเวอร์ชั่น 1.1 จะต้องเด็ดกว่า 1.0 แน่ ในเวอร์ชั่นนี้จะเน้นไปที่การมาของ Cross Platform .NET Framework นั่นหมายถึงการนำเอา Common Language Runtime (CLR) ขนาดเล็กผนวกไปกับความสามารถทางมัลติมีเดียของเวอร์ชั่น 1.0 นอกจากนี้ยังมีความสามารถบางส่วนของ Windows Presentation Foundation (WPF) และ Net FX Library API และสุดท้ายที่จะลืมไม่ได้เลยก็คือ Dynamic Language Runtime (DLR) ครับ สรุปว่าในเวอร์ชั่น 1.1 จะมีฟีเจอร์เด่นๆ ดังนี้
  • มี Built-in CLR Engine ที่ทำให้การทำงานของ Silverlight ในเบราว์เซอร์มีประสิทธิภาพสูงขึ้นมาก เนื่องจากเป็น Core CLR ตัวเดียวกันที่มากับ .NET Framework ทุกวันนี้ ก็เลยมีระบบการจัดการเดียวกันไม่ว่าจะเป็นเรื่องของ Type, Garbage Collector (GC) หรือแม้แต่ JIT Engine ทำให้คุณสามารถเขียนโค้ดครั้งเดียวแล้วสามารถรันได้กับทั้ง Silverlight, ASP.NET, WinForm และ WPF Application และยังหมายถึงความเร็วที่มากขึ้นอีกด้วย เร็วขึ้นแค่ไหนน่ะเหรอครับ ก็ไม่มากมายอะไรแค่ประมาณ 250 เท่าของโค้ดที่เขียนด้วยจาวาสคริปต์เท่านั้นเองครับ
  • Silverlight จะมาพร้อมกับ Framework ที่พร้อมสมบูรณ์ และเป็นส่วนหนึ่งของ .NET Framework ปัจจุบัน ทำให้คุณสามารถใช้งาน Collections, Generics, Threading, Globalization, Networking และ LINQ ได้ด้วยการเขียนโค้ดแบบเดิม ทำให้ไม่ต้องเรียนรู้สิ่งใหม่มากนัก ประหยัดเวลา
  • ยิ่งไปกว่านั้นด้วย DLR ทำให้ Silverlight สนับสนุนการเขียนโปรแกรมด้วยภาษาที่นักพัฒนาถนัด ที่ประกาศออกมาแล้วว่าจะสนับสนุนก็มี VB, C#, JavaScript, IronPython และ IronRuby! เช่นเดียวกันกับ .NET ทุกภาษาจะทำงานผสานกันได้อย่างราบรื่น
  • เนื่องจาก Silverlight กำหนดส่วนอินเทอร์เฟสกับผู้ใช้ด้วยภาษา XAML ดังนั้นมันจึงเหมือนกันกับที่มีใน WPF (สำหรับผู้ที่ไม่คุ้นเคย ภาษา XAML = eXtensible Application Markup Language มีลักษณะคล้ายภาษา XML ใช้ในการกำหนดอินเทอร์เฟสรูปแบบต่างๆ ใน WPF เช่น <Button Text="OK"></Button> เป็นต้น) ดังนั้นมันจึงจะสนับสนุนบางส่วนของ WPF ด้วย เช่น เรื่องของการจัดการอีเวนท์, การผูกข้อมูลเข้ากับอินเทอร์เฟส หรือการจัดการรูปร่างหน้าตาของแอพพลิเคชั่น เป็นต้น
  • Silverlight จะอนุญาตให้เราควบคุม HTML DOM API ได้ นั่นหมายถึงว่าเราสามารถเขียนตัวจัดการอีเวนท์ของอีลิเมนท์ที่เป็น HTML เช่น ปุ่ม ได้ด้วย C# หรือ VB โดย Silverlight จะสร้างจาวาสคริปต์ภายในหน้าเพื่อเชื่อมมันเข้าด้วยกัน นอกจากนี้ยังมี JSON Serializer ที่สนับสนุนการแปลง Data Type ไปมาระหว่าง .NET และจาวาสคริปต์อีกด้วย ทำให้คุณสามารถส่งค่าตัวแปรจากจาวาสคริปต์ไปยังเมธอดที่เขียนด้วย C# หรือ VB และส่งค่าที่ซับซ้อนขึ้นเช่น Collections จาก C# หรือ VB กลับมาหาจาวาสคริปต์ได้โดยไม่มีปัญหาเรื่อง Type Conversion เป็นต้น
  • จะไม่ต้องใช้ ASP.NET บนเว็บเซิร์ฟเวอร์ ทำให้มีอิสระในการเลือกใช้งาน เช่น อาจจะใช้ Silverlight กับ LAMP (Linux, Apache, MySQL, PHP) ก็ย่อมได้อย่างไม่มีปัญหา อย่างไรก็ดีจะมีฟีเจอร์บางอย่างที่ ASP.NET สนับสนุนโดยเฉพาะ เพื่อเพิ่มความสะดวกในการใช้งาน เช่น การใช้งาน MeMBership, Roles, Profile ของ ASP.NET หรือการเรียกไปยังเว็บเซอร์วิสผ่าน Windows Communcation Foundation (WCF) หรือ ASMX (เว็บเซอร์วิสแบบธรรมดา) นอกจากนี้ยังจะมีเซิร์ฟเวอร์คอนโทรลเฉพาะที่ใช้สำหรับติดตั้ง Silverlight ลงในเพจอีกด้วย

ในงาน International Broadcasting Conference (IBC) ที่อัมสเตอร์ดัม ไมโครซอฟท์เตรียมโชว์ฟีเจอร์ใหม่ของ Silverlight 4 นั่นคือฟีเจอร์เกี่ยวกับมัลติมีเดียและการกระจายวิดีโอ

ฟีเจอร์แรกคือสนับสนุนการส่งวิดีโอแบบมัลติแคสต์ ทำให้ลดโหลดของวิดีโอเซิร์ฟเวอร์ลงได้ ฟีเจอร์ที่สองคือ DRM แบบออฟไลน์ ดาวน์โหลดวิดีโอไปก่อน แล้วดูทีหลังแต่จำกัดจำนวนครั้งหรือระยะเวลาได้ (จะคล้ายๆ กับ DRM ใน iTunes) เทคโนโลยี DRM นี้เรียกว่า PlayReady

ในฝั่งเซิร์ฟเวอร์ ไมโครซอฟท์ยังออก Internet Information Services (IIS) Media Services 3.0 เอาไว้ทำ Live Smooth Streaming และยังเปิดสเปกของ IIS Smooth Streaming Transport Protocol กับ Protected Interoperable File Format (PIFF) ให้ใช้สัญญาอนุญาตที่เปิดกว้างมากขึ้น เพื่อเรียกการสนับสนุนจากพันธมิตรในแวดวงสื่อ

ผมรู้สึกว่าหลังจาก Silverlight 2.0 เป็นต้นมานั้นพัฒนาเร็วมาก และฟีเจอร์ต่างๆ ที่เพิ่มเข้ามาก็ชัดเจนว่าไมโครซอฟท์มองไปถึงแพลตฟอร์มสำหรับมัลติมีเดียใน ยุคหน้านั่นเอง

แม้ว่าการปรับปรุงเวอร์ชั่นของ Silverlight ในครั้งนี้จาก Silverlight 4 มา Silverlight 5 จะมีฟีเจอร์ไม่โดดเด่น เหมือนตอน Silverlight 3 มาเป็น Silverlight 4 แต่ก็มีฟีเจอร์เด่น 10 อย่างที่นักพัฒนา Silverlight เห็นแล้วต้องชอบ ดังนี้:

1. Debug Data Binding Expressions by Using Breakpoints in XAML
2. Animations Made Easy with Transitions
3. Navigating Up the Visual Tree in Bindings using RelativeSource and Mode=FindAncestor
4. Binding View Events to the ViewModel Using Custom Markup Extensions
5. Changing Styles Runtime By Binding in Style Setters
6. Networking No Longer Happening on the UI Thread
7. Vector Based Printing
8. HTML Content and Additional Permissions Within Trusted Silverlight Application
9. 3D API
10. Smaller Enhancements: Text Clarity and Performance Improvements

เป็นไงกันบ้างครับ ความสามารถใหม่ๆ ของ Silverlight โดนใจท่านผู้อ่านกันบ้างหรือเปล่า โดยส่วนตัวผมคิดว่านี่เป็นการเปลี่ยนแปลงครั้งใหญ่เพราะเป็นการทำให้เราสามารถใช้ .NET CLR ได้บนแพลตฟอร์มต่างๆ อย่างจริงจังเป็นครั้งแรก แถมยังรวมเอาประสิทธิภาพมากมายที่จะทำให้การสร้างแอพพลิเคชั่นประเภท RIA มีคุณภาพสูงขึ้นด้วยครับ ในส่วนถัดไปเรามาลองดูเครื่องมือในการทำงานกันบ้างดีกว่า

เครื่องมือที่ใช้ในการทำงาน

สำหรับเครื่องไม้เครื่องมือนั้น อันที่จริงแล้วเนื่องจากอินเทอร์เฟสของ Silverlight สร้างโดยใช้ XAML เป็นหลัก และส่วนของสคริปต์โต้ตอบก็เป็นจาวาสคริปต์ ดังนั้นคุณไม่ต้องการเครื่องมือพื้นฐานใดๆ มากไปกว่า Text Editor ธรรมดาๆ ที่คุณชอบใช้ เช่น NotePad (หรือของผมเป็น DarkRoom) อย่างไรก็ดี เพื่อให้เกิดความสะดวกในการทำงานยิ่งขึ้น คุณสามารถดาวน์โหลดเครื่องมือต่างๆ ที่ช่วยในการทำงานที่เกี่ยวกับ Silverlight ได้ฟรีจากไมโครซอฟท์ครับ เครื่องมือที่ว่าก็อย่างเช่น
  • Microsoft Expression Design - เอาไว้สร้างไฟล์กราฟิกแบบ XAML ลักษณะการทำงานคล้าย Photoshop + Illustrator เมื่อสร้างไฟล์กราฟิกสำเร็จ สามารถ Export ออกมาเป็น XAML เพื่อใช้ใน Silverlight ได้ต่อไปดาวน์โหลด
  • Microsoft Expression Blend - ใช้ในการกำหนดสัดส่วนและคอมโพเนนท์ต่างๆ ของอินเทอร์เฟส เช่น อยากจะให้อินเทอร์เฟสมีรูปร่างหน้าตาแบบไหน มีอนิเมชั่นอย่างไร ปุ่มวางตรงไหน วิดีโอวางตรงไหน เอากราฟิกที่ได้จาก Expression Design มาใช้ตรงไหน อย่างไร เป็นต้นดาวน์โหลด
  • Microsoft Visual Studio  - เขียนโปรแกรมตอบโต้กับส่วนอินเทอร์เฟส "Orcars" จะสนับสนุน Intellisense สำหรับจาวาสคริปต์ ทำให้การเขียนและ Debug ทำได้ง่ายขึ้น เว็บไซต์ส่วนใหญ่แนะนำให้ดาวน์โหลดเวอร์ชั่น Profession ซึ่งใช้เนื้อที่ราว 5 GB มาลง แต่ผมใช้แค่ Visual Web Developer Expression Edition ซึ่งเป็นเวอร์ชั่นที่ใช้งานได้ฟรีของ Visual Studio เองก็เพียงพอครับดาวน์โหลด, Express Edition
  • Silverlight Plug-in และ SDK - Plug-in จำเป็นต้องใช้ในการรัน Silverlight ในเบราว์เซอร์ ส่วน SDK จะมาพร้อมกับจาวาสคริปต์ที่จำเป็นในการติดตั้ง Silverlight ในเบราว์เซอร์ พร้อมกับตัวอย่างโค้ดและ Documentation เพื่อย่นเวลาในการพัฒนาให้สั้นขึ้นดาวน์โหลด

บทสรุป

จะเห็นได้ว่าการมาของ Silverlight เป็นการปฏิวัติวงการอินเทอร์เน็ตครั้งหนึ่งที่ต้องจารึกไว้ในประวัติศาสตร์ของโลกไซเบอร์เลยทีเดียว ด้วยความสามารถในการสนับสนุนการสร้างแอพพลิเคชั่นแบบ RIA จะทำให้แอพพลิเคชั่นบนอินเทอร์เน็ตในอนาคตเปลี่ยนรูปโฉมไปอย่างมาก การสนับสนุนมัลติมีเดียและอนิเมชั่นด้วยคุณภาพที่ดีขึ้นจะทำให้ผู้ชมได้รับความบันเทิงและความพึงพอใจมากขึ้นในการเยี่ยมชมเว็บไซต์ นอกจากนี้ยังมีความเร็วและประสิทธิภาพในการทำงานสูงขึ้น เพราะใช้ Core CLR แบบเดียวกับ .NET Framework หลัก นักพัฒนาไม่จำเป็นต้องเรียนรู้สิ่งใหม่มากนัก ก็สามารถพัฒนางานได้อย่างรวดเร็ว ด้วยเครื่องมือที่พรั่งพร้อมตั้งแต่เริ่มออกแบบจนจบกระบวนการติดตั้ง Silverlight จึงเป็นทางเลือกหนึ่งที่น่าสนใจ ที่จะเลือกมาใช้กับการทำงานของคุณ

WCF RIA Services คืออะไร

WCF RIA Services

[WCF RIA Services Version 1 Service Pack 2 is compatible with either .NET framework 4 or .NET Framework 4.5, and with either Silverlight 4 or Silverlight 5.]
WCF RIA Services simplifies the development of n-tier solutions for Rich Internet Applications (RIA), such as Silverlight applications. A common problem when developing an n-tier RIA solution is coordinating application logic between the middle tier and the presentation tier. To create the best user experience, you want your RIA Services client to be aware of the application logic that resides on the server, but you do not want to develop and maintain the application logic on both the presentation tier and the middle tier. RIA Services solves this problem by providing framework components, tools, and services that make the application logic on the server available to the RIA Services client without requiring you to manually duplicate that programming logic. You can create a RIA Services client that is aware of business rules and know that the client is automatically updated with latest middle tier logic every time that the solution is re-compiled.
The following illustration shows a simplified version of an n-tier application. RIA Services focuses on the box between the presentation tier and the data access layer (DAL) to facilitate n-tier development with a RIA Services client.
RIA Services n-tier applicationRIA Services adds tools to Visual Studio 2010 that enable linking client and server projects in a single solution and generating code for the client project from the middle-tier code. The framework components support prescriptive patterns for writing application logic so that it can be reused on the presentation tier. Services for common scenarios, such as authentication and user settings management, are provided to reduce development time.

DomainContext.SubmitChanges Method

DomainContext.SubmitChanges Method (Action<SubmitOperation>, Object)


WCF RIA Services Version 1 Service Pack 2 is compatible with either .NET framework 4 or .NET Framework 4.5, and with either Silverlight 4 or Silverlight 5.]
Submits all pending changes to the domain service.
This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.


NameDescription
Public methodSubmitChanges()Submits all pending changes to the domain service.
Public methodSubmitChanges(Action<SubmitOperation>, Object)Submits all pending changes to the domain service.



public virtual SubmitOperation SubmitChanges(
Action<SubmitOperation> callback,
Object userState
)

Remarks




You use the SubmitChanges method to update, insert, or delete data. All of the pending changes are submitted in one operation. You provide a callback method when you have code that must execute after the asynchronous operation has finished. In the callback method, you can check for errors and update the user interface as needed.

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    _customerContext.SubmitChanges(OnSubmitCompleted, null);
}

private void RejectButton_Click(object sender, RoutedEventArgs e)
{
    _customerContext.RejectChanges();
    CheckChanges();
}

private void CustomerGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
{
    CheckChanges();
}

private void CheckChanges()
{
    EntityChangeSet changeSet = _customerContext.EntityContainer.GetChanges();
    ChangeText.Text = changeSet.ToString();

    bool hasChanges = _customerContext.HasChanges;
    SaveButton.IsEnabled = hasChanges;
    RejectButton.IsEnabled = hasChanges;
}

private void OnSubmitCompleted(SubmitOperation so)
{
    if (so.HasError)
    {
        MessageBox.Show(string.Format("Submit Failed: {0}", so.Error.Message));
        so.MarkErrorAsHandled();
    }
    CheckChanges();
}

วันพุธที่ 9 พฤษภาคม พ.ศ. 2555

Porting Your Application to Windows Phone

Porting Your Application to Windows Phone

           

How to: Combine Silverlight and the XNA Framework in a Windows Phone Application

How to: Combine Silverlight and the XNA Framework in a Windows Phone Application

        
This topic provides step-by-step instructions for creating a basic application that combines Silverlight and the XNA Framework. You can find this completed Silverlight/XNA Framework sample in the Code Samples for Windows Phone topic. There is also a more elaborate sample called MyLittleTeapot on the same page that demonstrates how to update the XNA Framework content by responding to gestures from the Silverlight input system.
TipTip:
Before continuing, read Using the Project Template that Combines Silverlight and XNA to understand the code created by the project template used in this article.
In the past, you were forced to decide whether to use Silverlight or the XNA Framework to build your Windows Phone application. While some classes could be shared across frameworks, only one framework could be used for visuals. Starting with Windows Phone OS 7.1, you can combine Silverlight and the XNA Framework into a single application by using the new SharedGraphicsDeviceManager and the UIElementRenderer class.
NoteNote:
The steps in the following procedure are for Visual Studio 2010 Express for Windows Phone. You may see some minor variations in menu commands or window layouts when you are using the add-in for Visual Studio 2010 Professional or Visual Studio 2010 Ultimate.

The first step in creating a Windows Phone Silverlight application is to create a new project.

To create a new project

  1. Make sure you have downloaded and installed the Windows Phone SDK. For more information, see Installing the Windows Phone SDK.
  2. Start Visual Studio 2010 Express for Windows Phone from the Windows Start menu. If the Registration window appears, you can either register or temporarily dismiss the window.
  3. Create a new project by selecting the File | New Project menu command.
  4. The New Project window is displayed. Expand the Visual C# templates, and then select the Silverlight for Windows Phone templates.
  5. Select the Windows Phone Silverlight and XNA Application template. Fill in the project Name with a name of your choice.
    GetStartedNewProjectSilverlightXNA
  6. Click OK. Visual Studio creates a new project and opens MainPage.xaml in the Visual Studio designer window.
    After creating the project, you may see an item in the Warning window that says something similar to: “The project 'SilverlightXNAAppLib' cannot be referenced. The referenced project is targeted to a different framework family (.NETFramework).” You can safely ignore this error. It is simply referring to naming differences between the Silverlight and XNA Framework assemblies.
  7. Make sure Windows Phone Emulator is selected in the target drop-down at the top of Visual Studio.
  8. Press F5 to run the project under Windows Phone Emulator.
  9. In the emulator, press the Change to game page button.
The default project uses the XNA Framework to clear the Windows Phone screen to the CornflowerBlue color. We will:
  • Add code to animate a rectangle on the screen
  • Add Silverlight button controls, creating a color panel, to change the color of the rectangle
  • Add a button to toggle the visibility of the color panel
The XNA Framework will render these controls and the animated rectangle.

Create and add different colored rectangles to the library content for the project.

To create new graphics library content

  1. Right-click on the following graphic and choose Save picture as….
    Red rectangle
  2. In the Save Picture dialog, navigate to the directory where you created your project.
  3. Save the picture as redRect.jpg in the XxxxLibContent directory, where Xxxx is the name of the project you entered in step 5 of the Creating a New Project section earlier in this topic.
  4. Do the same with the following two graphics, saving them as greenRect.jpg and blueRect.jpg, respectively.
    Green rectangle
    Blue rectangle
  5. In Solution Explorer, right-click XxxxLibContent (Content), where Xxxx is the name of the project you entered in step 5 of the Creating a New Project section earlier in this topic.
  6. In the context menu, choose Add > Existing Item….
  7. In the Add Existing Item dialog, select all 3 files by holding down the CTRL key while clicking blueRect.jpg, greenRect.jpg, and redRect.jpg.
  8. Click the Add button to add the graphics files to the project.

In this section, we will load the rectangles as graphics content and animate the currently selected rectangle.

To load and animate the graphics

  1. In Solution Explorer, expand GamePage.xaml by clicking the triangle to its left.
  2. In the code editor, open GamePage.xaml.cs by double-clicking it.
  3. Declare four Texture2D variables at class scope in the GamePage class.
    // The current rectangle
    Texture2D texture;
    
    // A variety of rectangle colors
    Texture2D redTexture;
    Texture2D greenTexture;
    Texture2D blueTexture;
    
  4. Scroll down to the OnNavigatedTo method.
  5. After the TODO: comment, add the following code:
    // If texture is null, we've never loaded our content.
    if (null == texture)
    {
        redTexture = contentManager.Load<Texture2D>("redRect");
        greenTexture = contentManager.Load<Texture2D>("greenRect");
        blueTexture = contentManager.Load<Texture2D>("blueRect");
    
        // Start with the red rectangle.
        texture = redTexture;
    }
    
  6. Declare two Vector2 variables at class scope in the GamePage class.
    // Used to move the rectangle around the screen
    Vector2 spritePosition;
    Vector2 spriteSpeed = new Vector2(100.0f, 100.0f);
    
  7. Replace the contents of the OnUpdate method with the following code.
    // Move the sprite by speed, scaled by elapsed time.
    spritePosition += spriteSpeed * (float)e.ElapsedTime.TotalSeconds;
    
    int MinX = 0;
    int MinY = 0;
    int MaxX = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width - texture.Width;
    int MaxY = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height - texture.Height;
    
    // Check for bounce.
    if (spritePosition.X > MaxX)
    {
        spriteSpeed.X *= -1;
        spritePosition.X = MaxX;
    }
    
    else if (spritePosition.X < MinX)
    {
        spriteSpeed.X *= -1;
        spritePosition.X = MinX;
    }
    
    if (spritePosition.Y > MaxY)
    {
        spriteSpeed.Y *= -1;
        spritePosition.Y = MaxY;
    }
    else if (spritePosition.Y < MinY)
    {
        spriteSpeed.Y *= -1;
        spritePosition.Y = MinY;
    }
    
  8. Replace the contents of the OnDraw method with the following code.
    SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
    
    // Draw the sprite
    spriteBatch.Begin();
    
    // Draw the rectangle in its new position
    spriteBatch.Draw(texture, spritePosition, Color.White);
    
    spriteBatch.End();
    
  9. Select Windows Phone Emulator as the target and press F5 to run your application. Click the Change to game page button and you should see something very similar to the following image.
    Silverlight XNA application animated rectangle

In this section, we use XAML to create a panel of Silverlight Button controls. The buttons enable the user to change the color of the rectangle. We’ll also add a button to toggle the visibility of the color panel. Using the UIElementRenderer class, these controls are rendered to a Texture2D, which is then painted on the screen in a SpriteBatch operation in the OnDraw method.

To add Silverlight controls

  1. In Solution Explorer, double-click GamePage.xaml to open it in the designer.
  2. Since we will be using XAML, replace the following comment:
    <!--No XAML content as the page is rendered entirely with XNA-->
    
    With the following XAML code.
    <!-- LayoutRoot is the root grid where all page content is placed. -->
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
    
        <!-- Toggle the visibility of the ColorPanel. -->
        <Button Grid.Row="0" x:Name="ColorPanelToggleButton" Click="ColorPanelToggleButton_Click" Margin="1,0,-1,0">Toggle Color Panel</Button>
    
        <!-- Arrange buttons in a horizontal line by using StackPanel. -->
        <StackPanel x:Name="ColorPanel" Grid.Row="2"  Height="100" Orientation="Horizontal" HorizontalAlignment="Center" Visibility="Visible">
            <!-- Buttons to set the rectangle to specific colors -->
            <Button Click="redButton_Click" HorizontalAlignment="Center" Height="75" VerticalAlignment="Center" BorderThickness="3" Background="Red" Width="75" />
            <Button Click="greenButton_Click" HorizontalAlignment="Center" Height="75" VerticalAlignment="Center" BorderThickness="3" Background="Lime" Width="75" />
            <Button Click="blueButton_Click" HorizontalAlignment="Center" Height="75" VerticalAlignment="Center" BorderThickness="3" Background="Blue" Width="75" />
        </StackPanel>
    </Grid>
    
    This XAML code creates a Grid element to contain all the other elements. It first defines the Grid to have three rows. By using the Auto keyword, the top row and the bottom row Height properties are defined by their content. Using the asterisk (*) for the middle row Height property makes that row take up all the remaining space between the other two rows.
    Next, the XAML defines a Button with the Click event handler set to a method called ColorPanelToggleButton_Click.
    The XAML then defines a StackPanel to hold the Button elements that make up our color panel. The StackPanel has the x:Name property set to ColorPanel. This name is used in the C# code to toggle the visibility of this panel.
    The Button elements each have their Background color set and a Click event handler assigned.
    The following figure shows what our application in the designer should look like.
    GetStartedSilverlightXNALayout

Now that we’ve added our controls and assigned names to the Click event handlers, we need to implement the handler methods.

To add event handlers

  1. In the Visual Studio code editor, open or switch to GamePage.xaml.cs.
  2. Scroll down to the end of the file, past the OnDraw method.
  3. Copy and paste the following code immediately after the OnDraw method.
    // Toggle the visibility of the StackPanel named "ColorPanel".
    private void ColorPanelToggleButton_Click(object sender, RoutedEventArgs e)
    {
        if (System.Windows.Visibility.Visible == ColorPanel.Visibility)
        {
            ColorPanel.Visibility = System.Windows.Visibility.Collapsed;
        }
        else
        {
            ColorPanel.Visibility = System.Windows.Visibility.Visible;
        }
    }
    
    This code simply toggles the Visibility property on the StackPanel that we named “ColorPanel” in the XAML code.
  4. After the ControlPanelToggleButton_Click handler, copy and paste the following three Click handlers for the color Button elements that we declared in the XAML.
    // Switch to the red rectangle.
    private void redButton_Click(object sender, RoutedEventArgs e)
    {
        texture = redTexture;
    }
    
    // Switch to the green rectangle.
    private void greenButton_Click(object sender, RoutedEventArgs e)
    {
        texture = greenTexture;
    }
    
    // Switch to the blue rectangle.
    private void blueButton_Click(object sender, RoutedEventArgs e)
    {
        texture = blueTexture;
    }
    
    These event handlers just set the Texture2D object that we use to render the rectangle on the screen, called “texture”, to point to the appropriately colored rectangle, which we already loaded in the OnNavigatedTo method.

Now that we have created the controls and coded the event handlers, all we need to do is render them on the screen.

To render Silverlight controls

  1. In the GamePage.xaml.cs file, declare a UIElementRenderer at class scope level in the GamePage class.
    // For rendering the XAML onto a texture
    UIElementRenderer elementRenderer;
    
  2. In the GamePage class constructor, declare a handler for the LayoutUpdated event.
    // Use the LayoutUpdate event to know when the page layout 
    // has completed so that we can create the UIElementRenderer.
    LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
    
  3. Implement the GamePage_LayoutUpdated event handler. The this parameter in the call to the UIElementRenderer constructor is referring to the GamePage class, which is partially defined by the XAML code in the GamePage.xaml file. The UIElementRenderer class takes the XAML elements that are derived from UIElement and renders them to a Texture2D object.
    void GamePage_LayoutUpdated(object sender, EventArgs e)
    {
      // Create the UIElementRenderer to draw the XAML page to a texture.
    
      // Check for 0 because when we navigate away the LayoutUpdate event
      // is raised but ActualWidth and ActualHeight will be 0 in that case.
      if ((ActualWidth > 0) && (ActualHeight > 0))
      {
        SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = (int)ActualWidth;
        SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = (int)ActualHeight;
      }
    
      if (null == elementRenderer)
      {
        elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
      }
    }
    
    NoteNote:
    You cannot remove the Silverlight UIElement specified in the UIElementRenderer constructor from the visual tree.
  4. Next, use the UIElementRenderer instance to draw the Silverlight controls on the screen. Find the OnDraw method in the GamePage.xaml.cs file. Add the following line of code before the call to spriteBatch.Begin. This is the code that actually renders the XAML into a buffer that can be accessed with the Texture property of the UIElementRenderer.
    // Render the Silverlight controls using the UIElementRenderer.
    elementRenderer.Render();
    
  5. Also in the OnDraw method, add the following line of code between the calls to spriteBatch.Begin and spriteBatch.End.
    // Using the texture from the UIElementRenderer, 
    // draw the Silverlight controls to the screen.
    spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
    
  6. Select Windows Phone Emulator as the target and press F5 to run your application. You should see something very similar to the following image.
    GetStartedSilverlightXNARunning
  7. Click the buttons in the color panel at the bottom of the application to switch the color of the animated rectangle.
  8. Click the Toggle Color Panel button at the top of the application to hide and show the color panel.

How to: Create Your First XNA Framework Application for Windows Phone

How to: Create Your First XNA Framework Application for Windows Phone

           
This topic introduces you to the steps needed to create a basic XNA Framework application for Windows Phone. You can find this completed Hello XNA Framework sample in Code Samples for Windows Phone.
NoteNote:
The steps in the following procedure are for Visual Studio 2010 Express for Windows Phone. You may see some minor variations in menu commands or window layouts when you are using the add-in for Visual Studio 2010 Professional or Visual Studio 2010 Ultimate.

The first step in creating an XNA Framework application for Windows Phone is to create a new project.

To create a new project

  1. Make sure you have downloaded and installed the Windows Phone SDK. For more information, see Installing the Windows Phone SDK.
  2. Launch Visual Studio 2010 Express for Windows Phone from the Windows Start menu. If the Registration window appears, you can register or temporarily dismiss it.
  3. Create a new project by selecting the File | New Project menu command.
  4. The New Project window will be displayed. Expand the Visual C# templates, and then select the XNA Game Studio 4.0 templates.
  5. Select the Windows Phone Game (4.0) template. Fill in the project Name as desired. You can also specify the Location and Solution name or leave the default values.
    GetStartedNewProjectXNA
  6. Click OK. The Windows Phone Platform selection window will appear. Select Windows Phone 7.1 for the Target Windows Phone Version.
    GetStartedSelectPlatformXNA
  7. Click OK. A new project will be created and the Game1.cs source file will be opened in Visual Studio.

The next step is to add content to your project, in this case a graphic object and a sound file.

To add content to the project

  1. Make sure the Solution Explorer is visible in Visual Studio. If it is not visible, select View | Other Windows | Solution Explorer to make it appear.
  2. The first item to add is a graphic file. This example will use the PhoneGameThumb.png file that was created by default in this project in the WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1 directory. You can use either PhoneGameThumb.png or your own graphic file, but for best results, the graphic object should be approximately 64 x 64 pixels in size.
    Right-click the Content node, in this case named WindowsPhoneGame1Content (Content), and select Add | Existing Item. Browse to your graphic file – in this case WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1\PhoneGameThumb.png and click Add. The graphic object will be added to the project.
    Select the graphic name in the Solution Explorer and then look at the file properties in the Properties window. Note the Asset Name of the graphic object, in this case PhoneGameThumb.
    GetStartedPropertiesXNA
  3. The next step is to add a sound file. This example will use the Windows Ding.wav sound file that ships with Microsoft Windows 7. Search for Windows Ding.wav on your computer and copy it to the WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1 directory. You can also use your own sound file, but a very short sound about 1 second long is preferred.
    Right-click the Content node, in this case named WindowsPhoneGame1Content (Content), and select Add | Existing Item. Browse to your sound file – in this case WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1\Windows Ding.wav and click Add. The sound file will be added to the project.
    Select the sound file in the Solution Explorer and then look at the file properties in the Properties window. Note the Asset Name of the sound, in this case Windows Ding.

In this step, you will add the code that will move two graphic objects around the screen, detect when the graphic objects collide, and play a sound when the graphic objects collide. Look at the code that was added for you by default in the project. The framework of the game application has been provided. The next steps will take you through the process of:
  • Adding some variables.
  • Loading your graphic objects and sound assets in the LoadContent method.
  • Drawing your graphic objects on the screen in the Draw loop.
  • Updating the position of the graphic objects and detecting a collision in the Update loop.

To add code

  1. Copy and paste the following variables into your Game1 class and place the variables after the existing SpriteBatch spriteBatch variable. There are pairs of variables to track each graphic object, its position, its speed, its height, and its width. There is also one variable to hold our sound effect.
            Texture2D texture1;
            Texture2D texture2;
            Vector2 spritePosition1;
            Vector2 spritePosition2;
            Vector2 spriteSpeed1 = new Vector2(50.0f, 50.0f);
            Vector2 spriteSpeed2 = new Vector2(100.0f, 100.0f);
            int sprite1Height;
            int sprite1Width;
            int sprite2Height;
            int sprite2Width;
    
            SoundEffect soundEffect;
    
    
  2. Replace the LoadContent method with the following lines of code. This code will load the graphic object twice. Later on, you can add a second graphic object to the project so that you can have two different graphic objects bouncing about the screen. Each graphic object is given an initial position on the screen and the height and width of each are calculated.
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
    
        texture1 = Content.Load<Texture2D>("PhoneGameThumb");
        texture2 = Content.Load<Texture2D>("PhoneGameThumb");
      
        soundEffect = Content.Load<SoundEffect>("Windows Ding");
    
        spritePosition1.X = 0;
        spritePosition1.Y = 0;
    
        spritePosition2.X = graphics.GraphicsDevice.Viewport.Width - texture1.Width;
        spritePosition2.Y = graphics.GraphicsDevice.Viewport.Height - texture1.Height;
    
        sprite1Height = texture1.Bounds.Height;
        sprite1Width = texture1.Bounds.Width;
    
        sprite2Height = texture2.Bounds.Height;
        sprite2Width = texture2.Bounds.Width;
    }
    
    
  3. Replace the Draw method with the following lines of code. This code will draw each graphic object on the screen at its current position. They are given a different BlendState so that they appear slightly different since this example uses the same graphic file for each sprite.
    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // Draw the sprite.
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
        spriteBatch.Draw(texture1, spritePosition1, Color.White);
        spriteBatch.End();
    
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.Opaque);
        spriteBatch.Draw(texture2, spritePosition2, Color.Gray);
        spriteBatch.End();
    
        base.Draw(gameTime);
    
    }
    
    
  4. Replace the Update method with the following lines of code. The code also adds the UpdateSprite and CheckForCollision methods. The new code in the Update method will instruct each sprite to update their position in the UpdateSprite method. The UpdateSprite method also checks to see if the sprite hits a side, and if it does, changes its direction. Finally, Update calls CheckForCollision which checks to see if the bounds of each graphic object intersect with each other. If they do, a sound is played.
    protected override void Update(GameTime gameTime)
    {
        // Allow the game to exit.
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
            ButtonState.Pressed)
            this.Exit();
    
        // Move the sprite around.
        UpdateSprite(gameTime, ref spritePosition1, ref spriteSpeed1);
        UpdateSprite(gameTime, ref spritePosition2, ref spriteSpeed2);
        CheckForCollision();
    
        base.Update(gameTime);
    }
    
    void UpdateSprite(GameTime gameTime, ref Vector2 spritePosition, ref Vector2 spriteSpeed)
    {
        // Move the sprite by speed, scaled by elapsed time.
        spritePosition +=
            spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
    
        int MaxX =
            graphics.GraphicsDevice.Viewport.Width - texture1.Width;
        int MinX = 0;
        int MaxY =
            graphics.GraphicsDevice.Viewport.Height - texture1.Height;
        int MinY = 0;
    
        // Check for bounce.
        if (spritePosition.X > MaxX)
        {
            spriteSpeed.X *= -1;
            spritePosition.X = MaxX;
        }
    
        else if (spritePosition.X < MinX)
        {
            spriteSpeed.X *= -1;
            spritePosition.X = MinX;
        }
    
        if (spritePosition.Y > MaxY)
        {
            spriteSpeed.Y *= -1;
            spritePosition.Y = MaxY;
        }
    
        else if (spritePosition.Y < MinY)
        {
            spriteSpeed.Y *= -1;
            spritePosition.Y = MinY;
        }
    
    }
    
    void CheckForCollision()
    {
        BoundingBox bb1 = new BoundingBox(new Vector3(spritePosition1.X - (sprite1Width / 2), spritePosition1.Y - (sprite1Height / 2), 0), new Vector3(spritePosition1.X + (sprite1Width / 2), spritePosition1.Y + (sprite1Height / 2), 0));
    
        BoundingBox bb2 = new BoundingBox(new Vector3(spritePosition2.X - (sprite2Width / 2), spritePosition2.Y - (sprite2Height / 2), 0), new Vector3(spritePosition2.X + (sprite2Width / 2), spritePosition2.Y + (sprite2Height / 2), 0));
    
        if (bb1.Intersects(bb2))
        {
            soundEffect.Play();
        }
    
    }
    
    
    

The application is now complete. This step will let you build, run, and debug the application.

To build and debug the application

  1. Build the solution by selecting the Debug | Build Solution menu command. The project should build without any errors in the Error List windows. You can open the Error List window, if it is not already open, by selecting the View | Other Windows | Error List menu command. If there are errors, review the preceding steps, correct any errors, and then build the solution again.
  2. On the standard toolbar, set the deployment target of the application to Windows Phone Emulator.
    Target on Standard Toolbar selecting emulator
  3. Run the application by selecting the Debug | Start Debugging menu command. This will open the emulator window and launch the application. You will see two graphics bounce around the screen and play a sound when they are intersecting.
    GetStartedFirstAppRunningXNA
  4. If the emulator times out into the lock screen, you can unlock it by clicking at the bottom of the screen and swiping upward.
  5. You can set debug breakpoints in the code by placing the cursor on the desired line of code and selecting the Debug | Toggle Breakpoint menu command.
  6. To stop debugging, select the Debug | Stop Debugging menu command.
You have now created a basic XNA Framework application for Windows Phone. For more information about XNA Game Studio development, see XNA Game Studio 4.0.