Xamarin Forms WebView.CanGoBack always returns false on UWP - xamarin

Using the Xamarin Forms WebView control, I'm overriding the OnBackButtonPressed() and finding that the CanGoBack always returns false in UWP.
I don't see this problem in Android.
Is this a XF bug or am I doing something wrong?
Note: I'm running XF v2.3.3.193
EDIT: I upgraded to XF 2.3.4.247 and the problem persists.

I have created a code sample and reproduce your issue when the WebView browse several website. And I have found reason in the Xamarin.Forms source code.
void UpdateCanGoBackForward()
{
((IWebViewController)Element).CanGoBack = Control.CanGoBack;
((IWebViewController)Element).CanGoForward = Control.CanGoForward;
}
The CanGoBack property will be changed when UpdateCanGoBackForward method invoked. And UpdateCanGoBackForward method was called only when the native NavigationCompleted event was invoked. So if some website could not be loaded quickly, the CanGoBack property would not be changed.
You can improve this design by custom WebView. And you could follow the code below.
CustomWebView.cs
Add the new property for CustomWebView.
public class CustomWebView : WebView
{
public bool CCanGoBack { get; set; }
public CustomWebView()
{
}
}
CustomWebViewRenderer.cs
And change the property when the ContentLoading event invoked.
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace CustomWebViewTest.UWP
{
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.ContentLoading += Control_ContentLoading;
}
}
private void Control_ContentLoading(Windows.UI.Xaml.Controls.WebView sender, Windows.UI.Xaml.Controls.WebViewContentLoadingEventArgs args)
{
(Element as CustomWebView).CCanGoBack = Control.CanGoBack;
}
}
}
MainPage.cs
private void backClicked(object sender, EventArgs e)
{
if (Browser.CCanGoBack)
{
Browser.GoBack();
}
}

Related

Call UWP service on Shared project

I have a Xamarin app where I implemented a service to do some printing. I create that service on UWP app because it needs some dependencies of it.
UWP Service:
public class PrintUWPService
{
PrintManager printmgr = PrintManager.GetForCurrentView();
PrintDocument PrintDoc;
PrintDocument printDoc;
PrintTask Task;
private Windows.UI.Xaml.Controls.WebView ViewToPrint = new Windows.UI.Xaml.Controls.WebView();
public PrintUWPService()
{
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
public async void Print(WebView viewToPrint, string htmlSource)
{
ViewToPrint.NavigateToString(htmlSource);
if (PrintDoc != null)
{
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
printDoc.AddPages -= PrintDoc_AddPages;
}
printDoc = new PrintDocument();
try
{
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
printDoc.AddPages += PrintDoc_AddPages;
var showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
PrintDoc = null;
GC.Collect();
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deff = args.Request.GetDeferral();
Task = args.Request.CreatePrintTask("Grocery List", OnPrintTaskSourceRequested);
deff.Complete();
}
async void OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
args.SetSource(printDoc.DocumentSource);
});
def.Complete();
}
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
private void PrintDoc_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = Task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void PrintDoc_GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, ViewToPrint);
}
}
}
Then I create interface for it:
public interface IPrintUWPService
{
void Print(WebView viewToPrint, string htmlSource);
}
Now inside a class of my shared project I want to call this service as:
private readonly IPrintUWPService _printService = DependencyService.Get<IPrintUWPService>();
But it does not work. it says:
IPrintUWPService does not exist in the current context
So I try to access to UWP class as:
using MyCompany.ProjectName.App.UWP
But it says that "UWP" namespace does not exist. What am I doing wrong? is not possible call service on UWP project inside shared project? Regards
Call UWP DependencyService on Shared project
As #Jason mentioned in above comment, you need declare the interface in the Xamarin Forms project and implement it in the UWP client project.
And please note, after implementing the interface in each platform project, the platform implementations must be registered with the DependencyService, so that Xamarin.Forms can locate them at runtime. Use DependencyAttribute like the following.
[assembly: Dependency(typeof(UWP Client namesapce))]

How to disable Carousel Page scrolling in Android

Using a custom renderer one can disable the swiping gesture of an CarouselPage on iOS like so:
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace App.iOS
{
public class CustomCarouselPageRenderer : CarouselPageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
UIView view = this.NativeView;
UIScrollView scrollView = (UIKit.UIScrollView)view.Subviews[0];
scrollView.ScrollEnabled = false;
}
}
}
How to accomplish the same on Android?
using Android.Content;
using XamFormsApp.Droid.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace StixApp.Droid.Renderers
{
public class CustomCarouselPageRenderer : VisualElementRenderer<CarouselPage>
{
public CustomCarouselPageRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CarouselPage> e)
{
base.OnElementChanged(e);
var view = this.RootView;
X
X
}
}
}
There appears to be no way to access Subviews in the same way. One can access Children like so
Android.Views.View view = (Android.Views.View)GetChildAt(i);
How to know which Child is ScrollView if any?
Using a loop to check for this, like so,
for (int i = 0; i < ChildCount; ++i)
{
Android.Views.View view = (Android.Views.View)GetChildAt(i);
if (view is ScrollView)
{
}
}
Yields the following: "The given expression is never of the provided (ScrollView) type"
So! How to disable CarouselPage swipe/scrolling as is done in iOS quite elegantly?
UPDATE: Please see sample solution.
A couple of things.
For Android the view you are looking for is not a ScrollView but a ViewPager.
This can be found under the index 0 with the GetChildAt method.
Also, why are you using VisualElementRenderer<CarouselPage> as the parent class of your CustomCarouselPageRenderer. Instead use the CarouselPageRenderer as you did with iOS.
One last thing is that on Android the Scroll of a ViewPager cannot be disabled. To get this behavior you can listen to the Touch event. Setting the Handled property of TouchEventArgs to true will prevent the scrolling from happening.
Your whole class would look something like:
[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace StixApp.Droid.Renderers
{
public class CustomCarouselPageRenderer : CarouselPageRenderer
{
private bool _canScroll = false;
public CustomCarouselPageRenderer(Context context) : base(context)
{
}
public CustomCarouselPageRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CarouselPage> e)
{
base.OnElementChanged(e);
if (this.ChildCount > 0 && this.GetChildAt(0) is ViewPager viewPager)
{
viewPager.Touch -= ViewPagerTouched;
viewPager.Touch += ViewPagerTouched;
}
}
private void ViewPagerTouched(object sender, TouchEventArgs e)
{
e.Handled = !_canScroll;
}
}
}
Just change the value of _canScroll to true to allow the scrolling.
Hope this helps.-
Overridden Methods in ViewPager class:
public class NonSwipeableViewPager : ViewPager
{
public override bool OnTouchEvent(MotionEvent e)
{
return false;
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
return false;
}
public override bool ExecuteKeyEvent(KeyEvent ev)
{
return false;
}
}
Changes to CarouselPageRenderer:
In class declaration:
public class MyCarouselPageRenderer : VisualElementRenderer<CarouselPage>
{
NonSwipeableViewPager _viewPager;
}
In OnElementChanged:
protected override void OnElementChanged(ElementChangedEventArgs<CarouselPage> e)
{
_viewPager = new NonSwipeableViewPager(Context);
}
Note: CarouselPageAdapter, CarouselPageRenderer, MeasureSpecFactory, ObjectJavaBox, and PageContainer all had to be copied from the Xamarin.Forms github to enable a custom CarouselPageRenderer implementation. All of this is in the github sample but hopefully this spells it out more clearly for future visitors.
Note2: I would like to stress that the true behavior we were trying to achieve is probably best done with a NavigationPage as this allows us to easily pop and push any and all pages at any time without having to address the swipe issue. That being said, hopefully this solution serves to aid anyone who need this behavior on a CarouselPage.

ObservableCollection made of strings Not updating

Ok, so, I'm trying to link an ObservableCollection from my Android project to my Cross-Platform Project::
I've got this so far...this is in my Cross-platform app
ObservableCollection<String> NewRef = DependencyService.Get<ISlateBluetoothItems>().test().testThing;
NewRef.CollectionChanged += TestThing_CollectionChanged;
listView.ItemsSource = NewRef;
private void TestThing_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
listView.ItemsSource = DependencyService.Get<ISlateBluetoothItems>().test().testThing;
Console.WriteLine("working");
}
The line "working" is never printed even if I make changes to the ObservableCollection on the android portion of my app...
Here's the interface I'm using for the DependencyService:
using System.Collections.ObjectModel;
namespace ThoughtCastRewrite.BluetoothX
{
public interface ISlateBluetoothItems
{
BluetoothItems test();
}
}
Here's the class I use to expose the list:
namespace ThoughtCastRewrite.BluetoothX
{
public class BluetoothItems
{
public ObservableCollection<String> testThing;
public BluetoothItems()
{
testThing = new ObservableCollection<String>();
testThing.Add("wtf?");
}
public void AddThis()
{
testThing.Add("ok");
}
}
}
This is in the Android portion of my app, it implements the ISlateBluetoothItems interface
BluetoothItems bluetoothItems = new BluetoothItems();
then I call
bluetoothItems.AddThis();
but "ok" is not added to my list! I don't get the CollectionChanged event firing off! What's the deal guys? What's the deal?
You should assign your ObservableCollection as a source of your listview only once, not after each change. Changes to the collection will be automaticcly propagated to the listview.

How to detect when MvxListView is bound and has loaded its bindings?

I've Inherted MvxListView to my CustomMvxListView where I dos something with the visualization when a child has been added or removed.
It works great but can be laggy when many items get bound.
Is there a way to detect when Mvx view controls are bound and loaded there first bound data?
Found a good solution myself;
To track Itemsource changes in Android in a ListView you can use a DataSetObserver.
like:
internal class MyObserver : DataSetObserver
{
private readonly object view;
public MvxListViewNonScrollableObserver(ViewToTrack view)
{
tView = view;
DoSomething():
}
public override void OnChanged()
{
base.OnChanged();
DoSomething():
}
}
Add it to a ListView by:
class MyMvxListView : MvxListView
{
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
itemsourceObserver = new MyObserver(this);
Adapter.RegisterDataSetObserver(itemsourceObserver);
}
protected override void OnDetachedFromWindow()
{
if (itemsourceObserver != null)
{
Adapter.UnregisterDataSetObserver(itemsourceObserver);
itemsourceObserver = null;
}
base.OnDetachedFromWindow();
}
public void DoSomething()
{
}
DoSomething() get raised after load and on every itemsource change.

Can't Make Caliburn.Micro Work With Windows Phone

I'm trying to understand how Caliburn.Micro works with Windows Phone (and MVVM in general) so I created a basic Windows Phone Application, installed Caliburn.Micro NuGet package (v1.2.0 - the latest for now) and followed the few instructions here and there. So, I ended up with:
WMAppManifest.xml
<DefaultTask Name ="_default" NavigationPage="Views/HomeView.xaml"/>
Framework/AppBootstrapper.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using Caliburn.Micro;
using MyCaliburn.PhoneUI.ViewModels;
namespace MyCaliburn.PhoneUI.Framework
{
public class AppBootstrapper : PhoneBootstrapper
{
PhoneContainer container;
protected override void Configure()
{
container = new PhoneContainer(RootFrame);
container.RegisterPhoneServices();
container.Singleton<HomeViewModel>();
}
protected override void OnUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
e.Handled = true;
}
else
{
MessageBox.Show("An unexpected error occured, sorry about the troubles.", "Oops...", MessageBoxButton.OK);
e.Handled = true;
}
base.OnUnhandledException(sender, e);
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
}
}
ViewModels/HomeViewModel.cs
using Caliburn.Micro;
namespace MyCaliburn.PhoneUI.ViewModels
{
public class HomeViewModel : Screen
{
public HomeViewModel()
{
//DisplayName = "Home";
}
}
}
View/HomeView.xaml.cs (the XAML page is the default Window Phone Portrait Page)
using Microsoft.Phone.Controls;
namespace MyCaliburn.PhoneUI.Views
{
public partial class HomeView : PhoneApplicationPage
{
public HomeView()
{
InitializeComponent();
}
}
}
App.xaml
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyCaliburn.PhoneUI.App"
xmlns:Framework="clr-namespace:MyCaliburn.PhoneUI.Framework">
<!--Application Resources-->
<Application.Resources>
<Framework:AppBootstrapper x:Key="bootstrapper" />
</Application.Resources>
</Application>
App.xaml.cs
using System.Windows;
namespace MyCaliburn.PhoneUI
{
public partial class App : Application
{
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Standard Silverlight initialization
InitializeComponent();
}
}
}
Now, when I hit F5, the application runs and exits without showing any page or exception and doesn't hit any breakpoints that I sit.
Can anyone tells me what's missing in my code which prevents the application from running?
Thanks in advance.
Many times when I end up with an app that does not start - it turns out that due to some refactoring the App class is not the startup object any more. Right-click on the project in solution explorer, go to properties/Application and make sure Startup object is set correctly.

Resources