更新时间:2022-06-26 14:03:00
转自http://www.cnblogs.com/codelove/archive/2011/06/12/2079232.html
那么如何使Silverlight程序能够自适应浏览器窗口的大小呢,即使在动态改变浏览器窗口的时候也不例外。Google了几次,都没找到自己所需要的方案,于是只好自己来解决了。
首先,有没有办法在Silverlight的程序代码中获取浏览器的高宽呢?这一点似乎没法做 到,Application.Current.Host.Content.ActualWidth和 Application.Current.Host.Content.ActualHeight获取的是插件的高宽。 BrowserInformation对象获取的虽然是浏览器的信息,但是没有高宽。那么可以不可以使用JS获取浏览器高宽呢,这当然是可行的。
获取浏览器高宽有了思路,那么怎么让程序自适应呢?于是想到了“window.onresize”事件。这样,问题就解决了,具体代码如下:
首先,在Silverlight中定义了如下方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/// <summary> /// 设置控件布局(根据窗口来自适应) /// </summary> [ScriptableMember()] public void SetLayout( string _winWidth, string _winHeight)
{ double _windowWidth = Convert.ToDouble(_winWidth);
double _windowHeight = Convert.ToDouble(_winHeight);
//设置滚动框宽度
svPlans.Width = _windowWidth - 8;
Canvas.SetLeft(spButtons, _windowWidth - 400);
Canvas.SetLeft(txtTitle, _windowWidth / 2 - 150);
Canvas.SetZIndex(cvShowProcess, 999);
Canvas.SetLeft(cvShowProcess, _windowWidth / 3);
Canvas.SetTop(cvShowProcess, 80);
//设置滚动框高度
svPlans.MaxHeight = _windowHeight - 54;
} |
事件就辛苦点,在里面写下如下代码:
1
2
3
4
5
6
7
8
9
|
//JS调用SetLayout函数来设置控件布局 HtmlPage.Window.Eval( @"
setTimeout( function () {slCtl.Content.PlanView.SetLayout(document.documentElement.clientWidth, document.documentElement.clientHeight);
window.onresize = function() {
slCtl.Content.PlanView.SetLayout(document.documentElement.clientWidth, document.documentElement.clientHeight);
}
}, 1000
);" );
|
如此一来,首次加载以及“window.onresize”事件都能够调用之前的布局方法实现自适应浏览器窗口了。上面的代码值得说明的 是,“slCtl.Content.PlanView”的PlanView对象在上一篇中已经提及如何在Silverlight中注册的了,如不明白,请 阅读Silverlight——施工计划日报表(三)。