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) 即可

发布了4 篇原创文章 · 获赞 1 · 访问量 3541

猜你喜欢

转载自blog.csdn.net/qq_29791013/article/details/79326438
今日推荐