全屏对于用户体验还是很重要的,虽然在网上已经有讲如何实现全屏的文章了,但不是很全面,也没有讲到onFullScreenChanged事件,在此就当作个学习笔记。
创建Silverlight插件的代码在此就不详细讲解了,如果大家有啥不清楚的,可以去看silverlight 1.0 SDK中的QuickStart教程。我们首先来添加一个onLoad事件的事件处理程序,叫做myLoad,如下面红色代码所示:
function createMySilverlightPlugin()


{
Silverlight.createObject(
"myxaml.xaml", // Source property value.
parentElement, // DOM reference to hosting DIV tag.
"mySilverlightPlugin", // Unique plug-in ID value.

{ // Per-instance properties.
width:'400', // Width of rectangular region of
// plug-in area in pixels.
height:'400', // Height of rectangular region of
// plug-in area in pixels.
inplaceInstallPrompt:false, // Determines whether to display
// in-place install prompt if
// invalid version detected.
background:'#00FFFFFF', // Background color of plug-in.
isWindowless:'true', // Determines whether to display plug-in
// in Windowless mode.
framerate:'24', // MaxFrameRate property value.
version:'1.0' // Silverlight version to use.
},

{
onError:null, // OnError property value --
// event handler function name.
onLoad:myLoad // OnLoad property value --
// event handler function name.
},
null); // Context value -- event handler function name.
}
然后我们添加对应的myLoad函数:
function myload(control,context,root)


{
control.Content.OnFullScreenChange = onFullScreenChanged;
}
这里的control表示整个插件对象,在实际开发中我们经常会用到这个对象。在这里我们为OnFullScreenChange添加一个相对应的事件处理函数,叫做onFullScreenChanged,这个事件会在每次全屏状态改变时触发,有了它你才可以在全屏切换时对控件的布局进行调整,从而适应容器大小的变化,使用户体验趋于完美。例如你可以把一些原本在非全屏下显示不下的内容展开,一旦从全屏切换回非全屏,再把这些内容折叠起来。
为了让大家能够更清楚地看到Silverlight Control尺寸的变化,我特地在myxaml.xaml中增加了两个TextBlock:text1和text2,分别显示宽度和高度。在没有全屏时,由于设置了width:400和height:400,所以一开始是400*400。请注意,这里所说的宽度和高度是指Silverlight Control的宽度和高度,与myxaml.xaml中Canvas的宽度和高度无关,这也是学习Silverlight时一个比较容易混淆的概念。
myxaml.xaml中有个Ellipse,其MouseLeftButtonDown事件与fullscreen函数相对应,而fullscreen中就是切换全屏的代码,如下所示:
function fullscreen(sender, keyEventArgs)


{
sender.GetHost().Content.FullScreen = !sender.GetHost().Content.FullScreen;
}
在onFullScreenChanged函数会更新那两个TextBlock为当前的宽度和高度值,同时还会计算Canvas的居中位置,并对Canvas的位置作调整,代码如下:
function onFullScreenChanged(sender, eventArgs)


{
control=sender.getHost();
control.content.findname("text1").Text=control.content.actualWidth.toString();
control.content.findname("text2").Text=control.content.actualHeight.toString();
circle1=control.content.findname("circle1");
tleft=(control.content.actualWidth-circle1["Width"])/2;
ttop=(control.content.actualHeight-circle1["Height"])/2;
tleft=tleft>0?tleft:0;
ttop=ttop>0?ttop:0;

circle1["Canvas.Left"]=tleft;
circle1["Canvas.Top"]=ttop;
}
这里的sender.getHost()很有用,用它你能够轻易的获得Silverlight Control 对象实例。
最后,我把源代码放上来,讲得不清楚的地方大家可以看源代码。
源代码下载地址:http://www.cnblogs.com/Files/tonyqus/fullscreen.zip