1. 程式人生 > >C++,C# UWP中用ScrollViewer代替WebView的滾動條(可更改樣式)

C++,C# UWP中用ScrollViewer代替WebView的滾動條(可更改樣式)

    在UWP軟體開發過程中,我們可能會用WebView來顯示一些資訊,但是又遇到一個問題,WebView的自帶滾動條在PC中太大太醜,但是在我們更改了ScrollBar的樣式後,發現WebView中的滾動條依舊是原來的樣子。。。

    我的思路是在WebView外套一個ScrollViewer,然後呼叫JS返回頁面高度,然後將其賦值給webview的Height引數。因為在webview的高度大於等於頁面高度時,就不會出現滾動條。

下面則是我的解決方案,推薦寫在WebView的NavigationCompleted事件裡。

C++

static auto jsArray = ref new Platform::Collections::Vector<Platform::String^>;

jsArray->Append("document.documentElement.scrollHeight.toString();");//新增引數

static Windows::Foundation::Collections::IIterable<Platform::String^>^ myWebScript = jsArrary;

//注意這裡的IIterable<T>^不支援lambda,而且得用Vector<T>^來初始化

//還有這些引數是static的原因是因為在下面需要在 執行緒 中訪問它們

concurrency::create_task(webview->InvokeScriptAsync("eval", jsArray)).then([this](Platform::String^ webHeight)

{

    webview->Height = wtoi(webHeight->Data());//將Platform::String轉換為int並賦值給webview的Height引數

}, concurrency::task_continuation_context::use_current());//在UI執行緒執行

C#

webview.Height = Convert.ToInt32(await webview.InvokeScriptAsync("eval", "document.documentElement.scrollHeight.toString();"));

Xaml

<ScrollViewer>

    <WebView Name="webview"/>

</ScrollViewer>

順便說一下,ScrollBar的美化,可以在模板裡把上下兩個按鈕刪除,把中間的Rectangle設定RadiusX、RadiusY,大概5到7左右自己把控。最後上一張效果圖(WebView在右邊)


目前發現一個問題就是在觸控裝置中你的觸控焦點還是會在WebView上,但是在觸控裝置中的滾動條是不會擋內容的所以我相出以下解決方案,

在啟動時判斷通過Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily來判斷你的應用執行在PC或Mobile裝置上來決定是否要更改WebView高度,但是一旦我們遇到了可觸控的平板、筆記本之類的,這招就不是很管用了

因此我找到了另一種解決方案,

C#

bool isTouchDevice;

var touchCapabilities = new Windows.Devices.Input.TouchCapabilities();

isTouchDevice = touchCapabilities->TouchPresent != 0 ? false : true;

C++

bool isTouchDevice;

auto touchCapabilities = ref new Windows::Devices::Input::TouchCapabilities;

isTouchDevice = touchCapabilities->TouchPresent ? true : false;

判斷touchCapabilities.TouchPresent是否為0,如果是0,則不具備觸控功能,否則相反

接著只需要在你執行js並改變高度的語句部分加上個if(!isTouchDevice) 即可