環境搭建好了,下面從一個最簡單的應用程序開始練習SilverLight編程。
打開VisualStudio2008,添加新項目(筆者習慣C#編程):
在解決方案瀏覽器中默認會有App.xaml和Page.xaml,App.xaml是啓動入口,Page.xaml就是咱們的一個SilverLight程序。你能夠在項目中建立多個xaml文件
具體如圖:
解決方案瀏覽器:
這裏咱們用編寫代碼的方式設計界面,效果以下
Page.xaml代碼以下:
<
UserControl
x:Class
="SilverlightApplication1.Page"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Width
="400"
Height
="300"
>
<
Grid
x:Name
="LayoutRoot"
Background
="White"
>
<
Button
x:Name
="myButton"
Content
="點我"
Width
="200"
Height
="50"
Foreground
="Red"
Click
="myButton_Click"
>
</
Button
>
</
Grid
>
</
UserControl
>
<
UserControl>
是SilverLight的根容器
<
Grid >是佈局容器,若是有Java Swing編程經驗的人,對這個理解會比較快一點。
<
Button >是一個按鈕
Page.xaml.cs代碼以下:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace SilverlightApplication1
![](http://static.javashuo.com/static/loading.gif)
{
public partial
class Page : UserControl
![](http://static.javashuo.com/static/loading.gif)
{
public Page()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
InitializeComponent();
![](http://static.javashuo.com/static/loading.gif)
}
private
void myButton_Click(
object sender, RoutedEventArgs e)
![](http://static.javashuo.com/static/loading.gif)
{
this.myButton.Content =
"Hello SilverLight!";
this.myButton.Background =
new SolidColorBrush(Colors.Red);
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
}
實現若是點擊按鈕,則在按鈕上顯示
"Hello SilverLight!",
而且按鈕背景色變爲紅色。
運行測試和其它應用程序一致,點擊運行圖表或者菜單項就能夠了。
運行效果以下:
OK,從建立項目到建立xaml文件,這是咱們接下來不斷重複的步驟。