在很多情況下,從用戶體驗的角度考慮,我們都希望我們的Silverlight程序能夠適應各種大小的瀏覽器窗口或者框架,如圖所示:



那么如何使Silverlight程序能夠自適應瀏覽器窗口的大小呢,即使在動態改變瀏覽器窗口的時候也不例外。Google了幾次,都沒找到自己所需要的方案,于是只好自己來解決了。
首先,有沒有辦法在Silverlight的程序代碼中獲取瀏覽器的高寬呢?這一點似乎沒法做 到,Application.Current.Host.Content.ActualWidth和 Application.Current.Host.Content.ActualHeight獲取的是插件的高寬。 BrowserInformation對象獲取的雖然是瀏覽器的信息,但是沒有高寬。那么可以不可以使用JS獲取瀏覽器高寬呢,這當然是可行的。
獲取瀏覽器高寬有了思路,那么怎么讓程序自適應呢?于是想到了“window.onresize”事件。這樣,問題就解決了,具體代碼如下:
首先,在Silverlight中定義了如下方法:
05 |
public void SetLayout(string _winWidth, string _winHeight) |
07 |
double _windowWidth = Convert.ToDouble(_winWidth); |
08 |
double _windowHeight = Convert.ToDouble(_winHeight); |
10 |
svPlans.Width = _windowWidth - 8; |
11 |
Canvas.SetLeft(spButtons, _windowWidth - 400); |
12 |
Canvas.SetLeft(txtTitle, _windowWidth / 2 - 150); |
13 |
Canvas.SetZIndex(cvShowProcess, 999); |
14 |
Canvas.SetLeft(cvShowProcess, _windowWidth / 3); |
15 |
Canvas.SetTop(cvShowProcess, 80); |
17 |
svPlans.MaxHeight = _windowHeight - 54; |
該函數是可以使用JS調用的,上一篇已經說明了,這里就略過了。布局的方法寫好了,該寫js去調用了。由于不想每個頁面都寫調用的js,于是UserControl_Loaded
事件就辛苦點,在里面寫下如下代碼
1 |
//JS調用SetLayout函數來設置控件布局 |
2 |
HtmlPage.Window.Eval(@" |
4 |
function () {slCtl.Content.PlanView.SetLayout(document.documentElement.clientWidth, document.documentElement.clientHeight); |
5 |
window.onresize = function() { |
6 |
slCtl.Content.PlanView.SetLayout(document.documentElement.clientWidth, document.documentElement.clientHeight); |
如此一來,首次加載以及“window.onresize”事件都能夠調用之前的布局方法實現自適應瀏覽器窗口了
標簽:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:博客園