您的位置:首页 > 其它

Silverlight学习(一) 创建Silverlight项目,构建一个简单的Silverlight Demo

2009-08-26 09:13 901 查看
今天我将开始我的Silverlight学习之旅。首先学会如何创建Silverlight项目并构建一个Silverlight简单的Hello World Demo。

创建项目

现在Silverlight已经在短短的22个月里发展到Silverlight 3了,先安装Sliver 3(只能在VS2008 sp1上安装)。

安装完Silverlight后,启动VS2008,新建项目(快捷键CTRL+SHIFT+N),选择Visual C#,选择Silverlight,会看到如图供选择的模板:



选择Silverlight应用程序,点确定。由于Silverlight要依赖于一个网站项目,所以会有如下图的显示:



点确定,则会生成2个项目,一个是Silverlight项目,一个是Web项目。





制作一个简单的Silverlight效果


然后,你可以根据自己的需要修改Silverlight项目的命名空间(右键SilverlightHelloWorld,属性,在这里面修改)。

删除默认的MainPage.xaml文件(不删除,直接用也可以)。新建一个Silverlight控件HelloWorld.xaml。由于一个Silverlight项目只对应一个Silverlight控件,而原来的App.xaml文件的配置是:

private void Application_Startup(object sender, StartupEventArgs e)

{

this.RootVisual = new MainPage();

}

那么这里我们需要做如下修改:

private void Application_Startup(object sender, StartupEventArgs e)

{

this.RootVisual = new HelloWorld();

}

现在就可以按F5直接运行了,因为HelloWorld.xaml文件里面只有一个空的Grid,所以在页面上什么也看不见。

<UserControl x:Class="SilverlightHelloWorld.HelloWorld"

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">

</Grid>

</UserControl>

那么我们就为Grid添加一些元素看看效果吧。直接拖一个TextBlock控件,分别设置Grid和TextBlock得一些属性

<UserControl x:Class="SilverlightHelloWorld.HelloWorld"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

>

<Grid x:Name="LayoutRoot" Background="AliceBlue" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300" Height="300">

<TextBlock Name="txt" Text="Hello World" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="24" Foreground="#333333"></TextBlock>

</Grid>

</UserControl>

F5运行,将会看到如下效果:



为TextBlock加一个简单的左键事件:

<TextBlock Name="txt" Text="Hello World" FontSize="24" Foreground="#333333"

VerticalAlignment="Center" HorizontalAlignment="Center" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">

</TextBlock>

后台事件:

private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

this.txt.FontSize = 12;

this.txt.Text = "This is my first silverlight demo.";

}

在TextBlock区域点击鼠标左键得到如下效果:



以上就是一个最简单的Silverlight的Hello World例子,看起来比较简单吧。但是我觉得Silverlight有个缺点:所有需要把Silverlight效果加进去的页面都必须单独对应一个Silverlight项目,而不能把它们集合到一个Silverlight项目里面(因为this.RootVisual = new HelloWorld()限定了Silverlight要运行的xaml文件),如果能够把所有的Silverlight都集合到一个项目里面就很完美了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: