Custom entry null xamarin - xamarin

I created a custom entry in my Login page, but its getting null
I just created hte CustomEntry class and the CustomEntryRenderer, and put in the xaml file
My Login page .xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:custom="clr-namespace:HCTaNaMao.Customs"
x:Class="HCTaNaMao.Views.Login">
<ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand" Padding="0,100,0,0">
<Image Source="HCbackground.png" VerticalOptions="Center" HeightRequest="200" />
<Label Text="Usuario" HorizontalTextAlignment="Center"/>
<custom:CustomEntry
x:Name=" usernameEntry"
CornerRadius="18"
IsCurvedCornersEnabled="True"
BorderColor="LightBlue"
HorizontalTextAlignment="Start"
FontSize="17"
HeightRequest="40"
Placeholder="Usuário"
PlaceholderColor="LightGray"
TextColor="Black"
FontAttributes="Bold"
WidthRequest="100"/>
<Label Text="Senha" HorizontalTextAlignment="Center"/>
<custom:CustomEntry
x:Name=" passwordEntry"
CornerRadius="18"
IsCurvedCornersEnabled="True"
BorderColor="LightBlue"
HorizontalTextAlignment="Start"
FontSize="17"
HeightRequest="40"
Placeholder="Senha"
PlaceholderColor="LightGray"
TextColor="Black"
FontAttributes="Bold"
WidthRequest="100"
IsPassword="True"/>
<Button Text="Entrar" TextColor="White" Clicked="LoginUser" WidthRequest="110"
HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"/>
<Label x:Name="messageLabel" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
My Login page .xaml.cs
namespace HCTaNaMao.Views
{
public partial class Login : ContentPage
{
public static int seq_cliente;
public Login ()
{
InitializeComponent ();
usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());
}
async void LoginUser(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(usernameEntry.Text) || string.IsNullOrEmpty(passwordEntry.Text))
{
if (string.IsNullOrEmpty(usernameEntry.Text))
await DisplayAlert("Usuario", "Digite o Usuario", "OK");
else
await DisplayAlert("Senha", "Digite a Senha", "OK");
return;
}
HCTMWebService service = new HCTMWebService();
seq_cliente = service.Login(usernameEntry.Text.ToUpper());
if (seq_cliente > 0)
await Navigation.PopModalAsync();
else
await DisplayAlert("Erro Login", "Usuario ou Senha errado", "OK");
}
protected override bool OnBackButtonPressed()
{
#if __ANDROID__
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
#endif
return base.OnBackButtonPressed();
}
}
}
My custom entry
namespace HCTaNaMao.Customs
{
public class CustomEntry : Entry
{
public static readonly BindableProperty BorderColorProperty =
BindableProperty.Create(
nameof(BorderColor),
typeof(Color),
typeof(CustomEntry),
Color.Gray);
// Gets or sets BorderColor value
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
public static readonly BindableProperty BorderWidthProperty =
BindableProperty.Create(
nameof(BorderWidth),
typeof(int),
typeof(CustomEntry),
Device.OnPlatform<int>(1, 2, 2));
// Gets or sets BorderWidth value
public int BorderWidth
{
get { return (int)GetValue(BorderWidthProperty); }
set { SetValue(BorderWidthProperty, value); }
}
public static readonly BindableProperty CornerRadiusProperty =
BindableProperty.Create(
nameof(CornerRadius),
typeof(double),
typeof(CustomEntry),
Device.OnPlatform<double>(6, 7, 7));
// Gets or sets CornerRadius value
public double CornerRadius
{
get { return (double)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public static readonly BindableProperty IsCurvedCornersEnabledProperty =
BindableProperty.Create(
nameof(IsCurvedCornersEnabled),
typeof(bool),
typeof(CustomEntry),
true);
// Gets or sets IsCurvedCornersEnabled value
public bool IsCurvedCornersEnabled
{
get { return (bool)GetValue(IsCurvedCornersEnabledProperty); }
set { SetValue(IsCurvedCornersEnabledProperty, value); }
}
}
}
My renderer
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace HCTaNaMao.Droid
{
public class CustomEntryRenderer : EntryRenderer
{
public CustomEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var view = (CustomEntry)Element;
if (view.IsCurvedCornersEnabled)
{
// creating gradient drawable for the curved background
var _gradientBackground = new GradientDrawable();
_gradientBackground.SetShape(ShapeType.Rectangle);
_gradientBackground.SetColor(view.BackgroundColor.ToAndroid());
// Thickness of the stroke line
_gradientBackground.SetStroke(view.BorderWidth, view.BorderColor.ToAndroid());
// Radius for the curves
_gradientBackground.SetCornerRadius(
DpToPixels(this.Context,
Convert.ToSingle(view.CornerRadius)));
// set the background of the label
Control.SetBackground(_gradientBackground);
}
// Set padding for the internal text from border
Control.SetPadding(
(int)DpToPixels(this.Context, Convert.ToSingle(12)),
Control.PaddingTop,
(int)DpToPixels(this.Context, Convert.ToSingle(12)),
Control.PaddingBottom);
}
}
public static float DpToPixels(Context context, float valueInDp)
{
DisplayMetrics metrics = context.Resources.DisplayMetrics;
return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
}
}
}
In my Login.xaml.cs, the line
usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());
is getting error because the usernameEntry is null
Do I have to instance it?

In your XAML, you have x:Name=" usernameEntry" with a space. You must remove the space.

You need to instantiate your custom entry before adding a command. The correct way to use a custom entry is basically as the following example:
Add StackLayouts or another content layout
<StackLayout VerticalOptions="FillAndExpand" Padding="0,100,0,0">
<Image Source="HCbackground.png" VerticalOptions="Center" HeightRequest="200" />
<Label Text="Usuario" HorizontalTextAlignment="Center"/>
<StackLayout x:Name="stlUserName">
<!-- usernameEntry add here in code behind -->
</StackLayout>
<StackLayout x:Name="stlpasswordEntry">
<!-- passwordEntry add here in code behind -->
</StackLayout>
<Button Text="Entrar" TextColor="White" Clicked="LoginUser" WidthRequest="110"
HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"/>
<Label x:Name="messageLabel" />
</StackLayout>
In code behind instantiate your custom entry
public Login ()
{
InitializeComponent ();
CustomEntryRenderer usernameEntry = new CustomEntryRenderer();
usernameEntry.CornerRadius="18";
usernameEntry.IsCurvedCornersEnabled="True";
usernameEntry.BorderColor="LightBlue";
usernameEntry.HorizontalTextAlignment="Start";
usernameEntry.FontSize="17";
usernameEntry.HeightRequest="40";
usernameEntry.Placeholder="Usuário";
usernameEntry.PlaceholderColor="LightGray";
usernameEntry.TextColor="Black";
usernameEntry.FontAttributes="Bold";
usernameEntry.WidthRequest="100";
usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());
// Add entry in stacklayout
stlUserName.Children.Add(usernameEntry);
// do the same for password entry
}
Note:
Some properties of your entry, as CornerRadius, need to be added correctly, the above code just demonstrates that you need to instantiate your entry, add values to your properties, and add it to a stack layout.

Related

Xamarin iOS webview underlap behind navigation bar

I am using xamarin custom webview to load my page in app. But facing issue that title of webpage hides behind navigation bar . Or sometimes bottom of page not shown. I have tried adding scrollbar to my layout but still facing issue. Same works perfectly on android. Is it due to custom webview? I just want my webview to start below navigation bar and load completely according to device size.
my custom webview code :
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
Xaml Page :
<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
<StackLayout>
<Label x:Name="type" Text="Loading..." FontSize="Medium"/>
</StackLayout>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<ScrollView Orientation="Vertical" FlowDirection="MatchParent" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" Visual="Material" VerticalScrollBarVisibility="Always">
<OnPlatform x:TypeArguments="View">
<On Platform="Android">
<WebView x:Name="dashboard_android" HeightRequest="1000" WidthRequest="1000" />
</On>
<On Platform="iOS">
<local:CustomWebView x:Name="dashboard_ios" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand" WidthRequest="1000" HeightRequest="1000"/>
</On>
</OnPlatform>
</ScrollView>
</StackLayout>
</StackLayout>
code behind :
dashboard_android.Source = url;
dashboard_ios.Uri = url;
Following are solutions i have tried but no success
Solution 1 :
I have tried adding two properties, but no use
this.EdgesForExtendedLayout = UIRectEdge.None;
this.ExtendedLayoutIncludesOpaqueBars = false;
Solution 2 :
Tried enabling this unsafe area property , still no success
ios:Page.UseSafeArea="true"
Solution 3 :
Tried setting webview height on content size dynamically , but no success
public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
// base.DidFinishNavigation(webView, navigation);
var wv = _webViewRenderer.Element as CustomWebView;
if (wv != null)
{
await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
wv.HeightRequest = (double)webView.Frame.Size.Height; // ScrollView.ContentSize.Height;
}
}
Updated Xaml Code :
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<local:CustomWebView x:Name="dashboard" HeightRequest="1000" WidthRequest="1000" />
</StackLayout>
Updated Code behind :
public partial class DashboardView : ContentPage
{
string url;
public DashboardView()
{
InitializeComponent();
url= ""; //adding url to load here
dashboard.Uri = url;
}
}
Custom WebView Renderer
[assembly: ExportRenderer(typeof(CustomWebView), typeof(MyCustomWebViewRenderer))]
namespace Report.iOS
{
public class MyCustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
WKWebView webView;
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
webView = new WKWebView(Frame, new WKWebViewConfiguration());
webView.NavigationDelegate = new WebViewDelegate();
SetNativeControl(webView);
}
if (e.NewElement != null)
{
Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
}
}
}
public class WebViewDelegate : WKNavigationDelegate, INSUrlConnectionDataDelegate
{
string uname = null;
string pass = null;
public override async void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{
try
{
uname = Xamarin.Forms.Application.Current.Properties.ContainsKey("Username") ? Convert.ToString(Xamarin.Forms.Application.Current.Properties["Username"]) : null;
pass = await SecureStorage.GetAsync("Password");
}
catch (Exception ex)
{
}
completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(uname, pass, NSUrlCredentialPersistence.ForSession));
return;
}
}
}
Screenshot of webview screen :
Here i am loading this webpage(https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android). As you can see half of footer is hidden and i am not able to scroll it.
Screenshot of app
The reason for it quite simple actually you have added the WebView inside a scrollView which is, in turn, causing the issue webview has its own scroll so all you have to do is something like:
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<local:CustomWebView x:Name="dashboard" />
</StackLayout>
Also, you do not need the on the platform you can directly use the below and the custom renderer you have created.
The Height/Width request & layout options are not needed Webview by default will capture the whole viewport, You could actually even remove the StackLayouts, But that's on you.
Also, you might wanna read more about the webview
Good luck
Feel free to get back if you have queries
You can use latest WkWebViewRenderer:
public class MyCustomWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
//this.LoadUrl("https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android");
this.NavigationDelegate = new WebViewDelegate();
}
}
In your code behind, you can directly set the source or set your binding:
dashboard.Source = "https://learn.microsoft.com/en-us/xamarin/essentials/device-display?tabs=android";
Also, start from xamarin.forms 4.5+, xamarin use WKWebview as the default control in iOS and that means you no longer need a custom renderer if you use xamarin.forms 4.5+. Refer:
UIWebView Deprecation and App Store Rejection (ITMS-90809)
I was facing that issue just beacuse i was using custom renderer.
My solution code is as follows :
Xaml Code :
<ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<WebView x:Name="dashboard" HeightRequest="1000" WidthRequest="1000"/>
</StackLayout>
</ContentPage.Content>
Code Behind :
public partial class DashboardView : ContentPage
{
public DashboardView()
{
InitializeComponent();
dashboard.Source = "url";
}
}
Authentication Renderer iOS :
[assembly: ExportRenderer(typeof(WebView), typeof(Report.iOS.WebViewRenderer))]
namespace Report.iOS
{
class WebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
this.NavigationDelegate = new WebViewDelegate();
}
}
public class WebViewDelegate : WKNavigationDelegate, INSUrlConnectionDataDelegate
{
string uname = null;
string pass = null;
public override async void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{
try
{
uname = Xamarin.Forms.Application.Current.Properties.ContainsKey("Username") ? Convert.ToString(Xamarin.Forms.Application.Current.Properties["Username"]) : null;
pass = await SecureStorage.GetAsync("Password");
}
catch (Exception ex)
{
}
completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(uname, pass, NSUrlCredentialPersistence.ForSession));
return;
}
}
}
Authentication Renderer Android :
[assembly: ExportRenderer(typeof(WebView), typeof(AuthWebViewRenderer))]
namespace Report.Droid
{
public class AuthWebViewRenderer : Xamarin.Forms.Platform.Android.WebViewRenderer
{
AuthWebViewClient _authWebClient = null;
public AuthWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (_authWebClient == null)
{
_authWebClient = new AuthWebViewClient();
}
Control.SetWebViewClient(_authWebClient);
}
}
public class AuthWebViewClient : WebViewClient
{
public AuthWebViewClient()
{
}
public override async void OnReceivedHttpAuthRequest(global::Android.Webkit.WebView view, HttpAuthHandler handler, string host, string realm)
{
string uname = null;
string pass = null;
try
{
uname = Application.Current.Properties.ContainsKey("Username") ? Convert.ToString(Application.Current.Properties["Username"]) : null;
pass = await SecureStorage.GetAsync("Password");
}
catch (Exception ex)
{
Log.Error("Apprise :", "Error Occurred while getting login credentials " + ex);
}
handler.Proceed(uname, pass);
}
}
}

Adding content on a custom content page

Ok, so I am trying to add a searchbar in the toolbar of my page.
The Search bar appears correctly in the toolbar and I can catch the on text changed event.
I created a new Xaml and cs page and changed content page to 'MySearchContentPage'
I Tried to add a grid and label on my new page created but nothing will show except for the searchbar. I added this just to see if I can get anything to display.
Am I adding it in the right place ? Or how do you add content to this page ?
I have done this by doing the following:
MySearchContentPage Class:
public class MySearchContentPage : ContentPage, ISearchPage
{
public MySearchContentPage()
{
SearchBarTextChanged += HandleSearchBarTextChanged;
}
public event EventHandler<string> SearchBarTextChanged;
public void OnSearchBarTextChanged(string text) => SearchBarTextChanged?.Invoke(this, text);
void HandleSearchBarTextChanged(object sender, string searchBarText)
{
//Logic to handle updated search bar text
}
}
ISearchPage:
public interface ISearchPage
{
void OnSearchBarTextChanged(string text);
event EventHandler<string> SearchBarTextChanged;
}
iOS renderer page:
public class MySearchContentPageRenderer : PageRenderer, IUISearchResultsUpdating
{
readonly UISearchController searchController;
bool _isFirstAppearing = true;
public override void WillMoveToParentViewController(UIViewController parent)
{
base.WillMoveToParentViewController(parent);
var searchController = new UISearchController(searchResultsController: null)
{
SearchResultsUpdater = this,
DimsBackgroundDuringPresentation = false,
HidesNavigationBarDuringPresentation = true,
HidesBottomBarWhenPushed = true
};
searchController.SearchBar.Placeholder = "Search Symptoms";
parent.NavigationItem.SearchController = searchController;
DefinesPresentationContext = true;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
//Work-around to ensure the SearchController appears when the page first appears https://stackoverflow.com/a/46313164/5953643
if (_isFirstAppearing)
{
ParentViewController.NavigationItem.SearchController.Active = true;
ParentViewController.NavigationItem.SearchController.Active = false;
_isFirstAppearing = false;
}
}
public void UpdateSearchResultsForSearchController(UISearchController searchController)
{
if (Element is ISearchPage searchPage)
searchPage.OnSearchBarTextChanged(searchController.SearchBar.Text);
}
public MySearchContentPageRenderer()
{
var searchControllerr = new UISearchController(searchResultsController: null)
{
SearchResultsUpdater = this,
DimsBackgroundDuringPresentation = false,
HidesNavigationBarDuringPresentation = false,
HidesBottomBarWhenPushed = true
};
searchControllerr.SearchBar.Placeholder = string.Empty;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes
{
ForegroundColor = UIColor.Red
};
}
public override void ViewDidLoad()
{
// base.ViewDidLoad();
// NavigationController.NavigationBar.PrefersLargeTitles = true;
// NavigationController.NavigationBar.BackgroundColor = UIColor.Red;
// var searchController = new UISearchController(searchResultsController: null);
// searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Default;
// searchController.SearchBar.BackgroundColor = UIColor.Green;
// NavigationItem.SearchController = searchController;
// NavigationItem.HidesSearchBarWhenScrolling = false;
//searchController.SearchBar.SizeToFit();
//searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Prominent;
////NavigationController.TabBarController
//this.sea
//NavigationController.TabBarController.NavigationItem.HidesSearchBarWhenScrolling = true;
//NavigationController.TabBarController.NavigationItem.SearchController = searchController;
//this.Title = "Search";
}
}
So far the outcome is this :
I can't seem to get anything else to add to this page. Can anyone explain why?
AddSymptomNew.xaml page:
<?xml version="1.0" encoding="UTF-8"?>
<visiblegyapp:MySearchContentPage
xmlns:visiblegyapp="clr-namespace:VisiblegyApp"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="VisiblegyApp.AddSymptomNew"
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
ios:Page.LargeTitleDisplay="Always"
Title="Search Symptoms"
BackgroundColor="{DynamicResource BasePageColor}"
>
<ScrollView
x:Name="outerScrollView"
Padding="0"
>
<Grid
x:Name="layeringGrid"
RowSpacing="0"
VerticalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="test label" TextColor="Red" Grid.Row="1"/>
</Grid>
</ScrollView>
The cause is ContentPage is inheritable while XAML is not inheritable.
I would recommend you to use a custom contentview and add this contentView to MySearchContentPage .
For example, create a custom contentView here:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
And in Xaml:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="App132.AddSymptomNewView">
<ContentView.Content>
<ScrollView
x:Name="outerScrollView"
Padding="0">
<Grid
x:Name="layeringGrid"
RowSpacing="0"
VerticalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="test label" TextColor="Red" Grid.Row="1"/>
</Grid>
</ScrollView>
</ContentView.Content>
</ContentView>
And use it in the MySearchContentPage :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:app132="clr-namespace:App132"
mc:Ignorable="d"
x:Class="App132.MainPage">
<app132:AddSymptomNewView/>
</ContentPage>

Cannot display ListView data when creating PDF using PdfSharp.Xamarin.Forms

I am new to xamarin and I am using PdfSharp.Xamarin.Forms nuget to create a PDF in Xamarin forms for both Android and iOS. Problem is I cannot render ListView. They have mentioned about it, and need to write a renderer for it. But I have no idea how to create and bind it.
This is how I did it.
<Grid x:Name="mainGrid">
<ScrollView>
<StackLayout Padding="4" Orientation="Vertical">
<!--<Image HeightRequest="80" Source="logojpeg.jpg" Margin="0,0,0,5"/>-->
<Label FontSize="18" TextColor="Black" FontFamily="{StaticResource timesNewRomanBold}" HorizontalOptions="CenterAndExpand" Text="Monthly Motor Renew List of Jayasekara (900585) as at January, 2020"/>
<Label FontSize="18" TextColor="Black" FontFamily="{StaticResource timesNewRomanBold}" HorizontalOptions="CenterAndExpand" Text="Report generated on 27 December, 2019" Margin="0,0,0,5"/>
<ListView x:Name="renewListView"
Footer=""
pdf:PdfRendererAttributes.ListRendererDelegate="{StaticResource PDFSampleListRendererDelegate}"
BackgroundColor="White"
SeparatorVisibility="None"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell IsEnabled="false">
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ScrollView>
</Grid>
In code behind.
public partial class MotorRenewalFinalPrint : ContentPage
{
public MotorRenewalFinalPrint()
{
InitializeComponent();
}
public MotorRenewalFinalPrint (List<MotorRenewalPrintData> newdd)
{
InitializeComponent ();
Title = "Save as PDF";
renewListView.ItemsSource = newdd;
}
private void pdf_Clicked(object sender, EventArgs e)
{
var pdf = PDFManager.GeneratePDFFromView(mainGrid);
var fileManager = DependencyService.Get<IFileIO>();
string filePath = Path.Combine(fileManager.GetMyDocumentsPath(), "formpdf.pdf");
DependencyService.Get<IPdfSave>().Save(pdf, filePath);
DependencyService.Get<IPDFPreviewProvider>().TriggerPreview(filePath);
}
}
Updated...
MainClass
public partial class MainPage : ContentPage
{
private List<Customer> Cus = new List<Customer>();
public MainPage()
{
InitializeComponent();
Customer ss1 = new Customer { Names = "test1", Ages = "10"};
Customer ss2 = new Customer { Names = "test2", Ages = "30" };
Cus.Add(ss1);
Cus.Add(ss2);
//rListView.ItemsSource = Cus;
}
private void Button_Clicked(object sender, System.EventArgs e)
{
var pdf = PDFManager.GeneratePDFFromView(mainGrid);
var fileManager = DependencyService.Get<IFileIO>();
string filePath = Path.Combine(fileManager.GetMyDocumentsPath(), "testpdf.pdf");
DependencyService.Get<IPdfSave>().Save(pdf, filePath);
DependencyService.Get<IPDFPreviewProvider>().TriggerPreview(filePath);
}
}
view
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TestPDF"
xmlns:pdf="clr-namespace:PdfSharp.Xamarin.Forms;assembly=PdfSharp.Xamarin.Forms"
x:Class="TestPDF.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<local:PDFSampleListRendererDelegate x:Key="PDFSampleListRendererDelegate" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<Grid x:Name="mainGrid">
<ScrollView>
<StackLayout Margin="0,0,0,5">
<Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="CenterAndExpand" TextColor="Black" FontSize="18" VerticalOptions="Center" />
<ListView pdf:PdfRendererAttributes.ListRendererDelegate="{DynamicResource PDFSampleListRendererDelegate}" HeightRequest="150"/>
<Button Text="click" Clicked="Button_Clicked"/>
</StackLayout>
</ScrollView>
</Grid>
</ContentPage.Content>
</ContentPage>
PDFSampleListRendererDelegate
public class PDFSampleListRendererDelegate : PdfListViewRendererDelegate
{
public override void DrawCell(ListView listView, int section, int row, XGraphics page, XRect bounds, double scaleFactor)
{
XFont font = new XFont("times" ?? GlobalFontSettings.FontResolver.DefaultFontName, 15);
var yourObject = (listView.ItemsSource as List<Customer>).ElementAt(row);
page.DrawString(yourObject.Names, font, XBrushes.Black, bounds,
new XStringFormat
{
LineAlignment = XLineAlignment.Center,
Alignment = XStringAlignment.Center,
});
}
public override void DrawFooter(ListView listView, int section, XGraphics page, XRect bounds, double scaleFactor)
{
base.DrawFooter(listView, section, page, bounds, scaleFactor);
}
public override double GetFooterHeight(ListView listView, int section)
{
return base.GetFooterHeight(listView, section);
}
}
you should override DrawCell method
i.e:
public override void DrawCell(ListView listView, int section, int row, XGraphics page, XRect bounds, double scaleFactor)
{
XFont font = new XFont(yourCustomFont ?? GlobalFontSettings.FontResolver.DefaultFontName, label.FontSize * scaleFactor);
var yourObject = (listView.ItemSource as List<YourObjType>).ElementAt(row);
page.DrawString(yourObject.Text, font, XColors.Black, bounds,
new XStringFormat {
LineAlignment = XLineAlignment.Center,
Alignment = XStringAlignment.Center,
});
}

Xamarin ItemTemplate with a WebView control

I am trying to add a WebView control inside a ItemTemplate and set the height of the row. I know that I can't have the webview control scroll so I need to setting the height to the correct size to display the full html content. I have created an IValueConverter class that I was thinking can return the correct height needed but what height value to return depending on how long the content is?
Anyway I can load the webview and get the height needed to display the full content I get -1 for height in my writeline?
XAML Code
<telerikListView:ListViewTemplateCell>
<Grid BackgroundColor="{StaticResource LightBlueColor}"
Padding="10">
<telerikPrimitives:RadBorder Padding="10"
HorizontalOptions="Fill"
BorderThickness="2"
BorderColor="{StaticResource DarkBlueColor}"
BackgroundColor="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<!--<RowDefinition Height="*"/>-->
<RowDefinition Height="{Binding AssetItem.Description, Converter={StaticResource DescriptionToHeightConverter}}" />
</Grid.RowDefinitions>
<!--<Grid Grid.Row="0" Grid.Column="0">
<HtmlLabelControl:HtmlLabel
Text="{Binding AssetItem.Description}"
HeightRequest="100"/>-->
<WebView HeightRequest="800" MinimumHeightRequest="300" HorizontalOptions="FillAndExpand">
<WebView.Source>
<HtmlWebViewSource Html="{Binding AssetItem.Description}"/>
</WebView.Source>
</WebView>
<!--</Grid>-->
<!--<WebView Grid.Column="0" Grid.Row="0" HeightRequest="200" HorizontalOptions="FillAndExpand">
<WebView.Source>
<HtmlWebViewSource Html="{Binding AssetItem.Description}"/>
</WebView.Source>
</WebView>-->
<!--<Label Text="{Binding AssetItem.Description}"
TextColor="{StaticResource GrayTextColor}"
Grid.Row="0"
Grid.Column="0"/>-->
<!--Star-->
<telerikPrimitives:RadPath
x:Name="path"
Grid.Row="0"
Grid.Column="1"
WidthRequest="40"
HeightRequest="35"
StrokeThickness="2"
VerticalOptions="Start"
Fill="{Binding AssetItem.IsBookmark, Converter={StaticResource FavFillColorConverter}}"
Stroke="#3e7dc5"
Geometry="{x:Static telerikInput:Geometries.Star}">
<telerikPrimitives:RadPath.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="BookmarkCommand" CommandParameter="{Binding AssetItem.AssetId}" />
</telerikPrimitives:RadPath.GestureRecognizers>
</telerikPrimitives:RadPath>
</Grid>
<!--</Grid>-->
</telerikPrimitives:RadBorder>
</Grid>
</telerikListView:ListViewTemplateCell>
CS Converter Logic
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var description = value as string;
//WebView wv = new WebView();
//wv.Source = description;
HtmlWebViewSource HtmlSource = new HtmlWebViewSource();
HtmlSource.Html = description;
WebView webView = new WebView()
{
Source = HtmlSource
};
Debug.WriteLine($"Web View Height: {webView.Height}");
if (!string.IsNullOrEmpty(description))
{
if (description.Length == 300)
{
return 50;
}
}
return 300;
}
Test code
HtmlWebViewSource HtmlSource = new HtmlWebViewSource();
HtmlSource.Html = "<html><body><div><h1>MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM</h1></div></body></html>";
WebView webView = new WebView()
{
Source = HtmlSource
};
string htmlheight = "";
Task.Run(async () => {
try
{
htmlheight = await webView.EvaluateJavaScriptAsync("document.body.scrollHeight");
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
});
//WebView_NavigatedAsync(webView);
Debug.WriteLine($"Web View Height: {htmlheight}");
If you want to get the height of the html .You can implement by using Custom Renderer
in Forms
public MainPage()
{
InitializeComponent();
HtmlWebViewSource HtmlSource = new HtmlWebViewSource();
HtmlSource.Html = #"<html><body>
<h1>Xamarin.Forms</h1>
<p>Welcome to WebView.</p>
</body></html>";
Webview webView = new Webview()
{
WidthRequest = 100,
HeightRequest = 20,
Source =HtmlSource
};
MessagingCenter.Subscribe<Object, float>(this,"webview_loaded",(sender,value)=>{
Console.WriteLine(value); //value is the height of html
});
Content = new StackLayout
{
Children =
{
webView,
},
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions=LayoutOptions.FillAndExpand
};
}
in iOS project
using Foundation;
using UIKit;
using CoreGraphics;
using xxx;
using xxx.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly:ExportRenderer(typeof(WebView),typeof(MyWebViewRenderer))]
namespace App7.iOS
{
public class MyWebViewRenderer:WebViewRenderer,IUIWebViewDelegate
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if(NativeView!=null)
{
// WeakDelegate = this;
}
}
[Export("webViewDidFinishLoad:")]
public void LoadingFinished(UIWebView webView)
{
string htmlHeight = webView.EvaluateJavascript("document.body.scrollHeight");
float height = float.Parse(htmlHeight);
MessagingCenter.Send<System.Object, float>(this, "webview_loaded", height);
}
}
}
in Android
using Android.Content;
using Android.Webkit;
using Android.Widget;
using xxx;
using xxx.Droid;
using Java.Lang;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(MyWebViewRenderer))]
namespace xxx.Droid
{
public class MyWebViewRenderer:WebViewRenderer
{
public MyWebViewRenderer(Context context):base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if(Control!=null)
{
Android.Webkit.WebView webview =(Android.Webkit.WebView) Control;
WebSettings settings = webview.Settings;
settings.JavaScriptEnabled = true;
webview.SetWebViewClient(new JavascriptWebViewClient());
}
}
}
public class JavascriptWebViewClient : WebViewClient
{
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript("javascript:document.body.scrollHeight;", new EvaluateBack() );
}
}
class EvaluateBack : Java.Lang.Object, IValueCallback
{
public void OnReceiveValue(Java.Lang.Object value)
{
string htmlHeight = value.ToString();
float height = float.Parse(htmlHeight);
MessagingCenter.Send<System.Object, float>(this,"webview_loaded",height);
}
}
}
Notes: in your test code ,you get call the method when the html didn't finish loading ,so the result is -1.

How can I stop and start a timed progress bar in Xamarin?

There is a question with an answer that shows how a progress bar can be created that runs for a specified period of time. Here's a link to that question:
How can I create a bar area that slowly fills from left to right over 5, 10 or ?? seconds?
I have tested this out and it works well. However I would like to find out how I can extend this so that the progress bar can be cancelled / stopped before completed and then restarted again.
The question and answer were very popular so it seems like this is something that might benefit many people.
I would appreciate any ideas and feedback on possible ways this could be done.
Update 1:
I tried to implement the solution but I am getting an error and would appreciate some advice. I'm using all your new code and I change from the old to the new here:
<local:TimerView x:Name="timerView">
<local:TimerView.ProgressBar>
<BoxView BackgroundColor="Maroon" />
</local:TimerView.ProgressBar>
<local:TimerView.TrackBar>
<BoxView BackgroundColor="Gray" />
</local:TimerView.TrackBar>
</local:TimerView>
<!--<Grid x:Name="a">
<local:TimerView x:Name="timerView1" VerticalOptions="FillAndExpand">
<local:TimerView.ProgressBar>
<Frame HasShadow="false" Padding="0" Margin="0" BackgroundColor="#AAAAAA" CornerRadius="0" VerticalOptions="FillAndExpand" />
</local:TimerView.ProgressBar>
<local:TimerView.TrackBar>
<Frame HasShadow="false" Padding="0" Margin="0" CornerRadius="0" BackgroundColor="#EEEEEE" VerticalOptions="FillAndExpand" />
</local:TimerView.TrackBar>
</local:TimerView>
</Grid>
<Grid x:Name="b">
<local:TimerView x:Name="timerView2" VerticalOptions="FillAndExpand">
<local:TimerView.ProgressBar>
<Frame HasShadow="false" Padding="0" Margin="0" BackgroundColor="#AAAAAA" CornerRadius="0" VerticalOptions="FillAndExpand" />
</local:TimerView.ProgressBar>
<local:TimerView.TrackBar>
<Frame HasShadow="false" Padding="0" Margin="0" CornerRadius="0" BackgroundColor="#EEEEEE" VerticalOptions="FillAndExpand" />
</local:TimerView.TrackBar>
</local:TimerView>
</Grid>-->
Three questions
First - I noticed you split timerView into two files. The properties file appears to be in some way linked to the main file. Graphically the properties file appears indented from timerView. How do you do this linking in Visual Studio? I just created two files, does that make a difference.
Second - When I try to compile the code I am getting this error:
/Users//Documents/Phone app/Japanese7/Japanese/Views/Phrases/PhrasesFrame.xaml(10,10): Error: Position 117:10. Missing a public static GetProgressBar or a public instance property getter for the attached property "Japanese.TimerView.ProgressBarProperty" (Japanese)
Do you have any ideas what might be causing this? Everything looks the same as before.
Third - I notice you use BoxView and I used a Frame. Would the code work with either?
Update 2:
In my backend C# code I use the following to start the timer:
timerView.StartTimerCommand
.Execute(TimeSpan.FromSeconds(App.pti.Val()));
I tried to stop the timer with some similar syntax but there's some problem. Can you let me know how I can go about stopping the timer when it's used with C# back-end rather than the MVVM in your solution:
timerView.StopTimerCommand.Execute(); // Give syntax error
Step 1: Add cancel method to ViewExtensions:
public static class ViewExtensions
{
static string WIDTH_ANIMATION_NAME = "WidthTo";
public static Task<bool> WidthTo(this VisualElement self, double toWidth, uint length = 250, Easing easing = null)
{
...
}
public static void CancelWidthToAnimation(this VisualElement self)
{
if(self.AnimationIsRunning(WIDTH_ANIMATION_NAME))
self.AbortAnimation(WIDTH_ANIMATION_NAME);
}
}
Step 2: Add bindable properties for 'pause' and 'stop'/'cancel' commands; and a property to track whether timer is running.
public static readonly BindableProperty PauseTimerCommandProperty =
BindableProperty.Create(
"PauseTimerCommand", typeof(ICommand), typeof(TimerView),
defaultBindingMode: BindingMode.OneWayToSource,
defaultValue: default(ICommand));
public ICommand PauseTimerCommand
{
get { return (ICommand)GetValue(PauseTimerCommandProperty); }
set { SetValue(PauseTimerCommandProperty, value); }
}
public static readonly BindableProperty StopTimerCommandProperty =
BindableProperty.Create(
"StopTimerCommand", typeof(ICommand), typeof(TimerView),
defaultBindingMode: BindingMode.OneWayToSource,
defaultValue: default(ICommand));
public ICommand StopTimerCommand
{
get { return (ICommand)GetValue(StopTimerCommandProperty); }
set { SetValue(StopTimerCommandProperty, value); }
}
public static readonly BindableProperty IsTimerRunningProperty =
BindableProperty.Create(
"IsTimerRunning", typeof(bool), typeof(TimerView),
defaultBindingMode: BindingMode.OneWayToSource,
defaultValue: default(bool), propertyChanged: OnIsTimerRunningChanged);
public bool IsTimerRunning
{
get { return (bool)GetValue(IsTimerRunningProperty); }
set { SetValue(IsTimerRunningProperty, value); }
}
private static void OnIsTimerRunningChanged(BindableObject bindable, object oldValue, object newValue)
{
((TimerView)bindable).OnIsTimerRunningChangedImpl((bool)oldValue, (bool)newValue);
}
Step 3: Update TimerView as below to use a StopWatch to track time, pause, and cancel.
public partial class TimerView : AbsoluteLayout
{
readonly Stopwatch _stopWatch = new Stopwatch();
public TimerView()
{
...
}
async void HandleStartTimerCommand(object param = null)
{
if (IsTimerRunning)
return;
ParseForTime(param);
if (InitRemainingTime())
_stopWatch.Reset();
SetProgressBarWidth();
IsTimerRunning = true;
//Start animation
await ProgressBar.WidthTo(0, Convert.ToUInt32(RemainingTime.TotalMilliseconds));
//reset state
IsTimerRunning = false;
}
void HandlePauseTimerCommand(object unused)
{
if (!IsTimerRunning)
return;
ProgressBar.CancelWidthToAnimation(); //abort animation
}
void HandleStopTimerCommand(object unused)
{
if (!IsTimerRunning)
return;
ProgressBar.CancelWidthToAnimation(); //abort animation
ResetTimer(); //and reset timer
}
protected virtual void OnIsTimerRunningChangedImpl(bool oldValue, bool newValue)
{
if (IsTimerRunning)
{
_stopWatch.Start();
StartIntervalTimer(); //to update RemainingTime
}
else
_stopWatch.Stop();
((Command)StartTimerCommand).ChangeCanExecute();
((Command)PauseTimerCommand).ChangeCanExecute();
((Command)StopTimerCommand).ChangeCanExecute();
}
bool _intervalTimer;
void StartIntervalTimer()
{
if (_intervalTimer)
return;
Device.StartTimer(TimeSpan.FromMilliseconds(100), () =>
{
if(IsTimerRunning)
{
var remainingTime = Time.TotalMilliseconds - _stopWatch.Elapsed.TotalMilliseconds;
if (remainingTime <= 100)
{
_intervalTimer = false;
ResetTimer();
}
else
RemainingTime = TimeSpan.FromMilliseconds(remainingTime);
}
return _intervalTimer = IsTimerRunning; //stop device-timer if timer was stopped
});
}
private void ResetTimer()
{
ProgressBar.CancelWidthToAnimation();
RemainingTime = default(TimeSpan); //reset timer
SetProgressBarWidth(); //reset width
}
void SetProgressBarWidth()
{
if (RemainingTime == Time)
SetLayoutBounds(ProgressBar, new Rectangle(0, 0, Width, Height));
else
{
var progress = ((double)RemainingTime.Seconds / Time.Seconds);
SetLayoutBounds(ProgressBar, new Rectangle(0, 0, Width * progress, Height));
}
}
...
}
Sample Usage
<controls:TimerView x:Name="timerView">
<controls:TimerView.ProgressBar>
<BoxView BackgroundColor="Maroon" />
</controls:TimerView.ProgressBar>
<controls:TimerView.TrackBar>
<BoxView BackgroundColor="Gray" />
</controls:TimerView.TrackBar>
</controls:TimerView>
<Label Text="{Binding Path=RemainingTime, StringFormat='{0:%s}:{0:%f}', Source={x:Reference timerView}}" />
<Button Command="{Binding StartTimerCommand, Source={x:Reference timerView}}" Text="Start Timer">
<Button.CommandParameter>
<x:TimeSpan>0:0:20</x:TimeSpan>
</Button.CommandParameter>
</Button>
<Button Command="{Binding PauseTimerCommand, Source={x:Reference timerView}}" Text="Pause Timer" />
<Button Command="{Binding StopTimerCommand, Source={x:Reference timerView}}" Text="Stop Timer" />
Working sample uploaded at TimerBarSample
EDIT 1
First - It really doesn't make a difference - you can even merge all code into one file. Indented linking can be achieved using <DependentOn /> tag - similar to what is used for code-behind cs for XAML files.
Second - I had added protected access-modifiers to bindable properties' getters or setters. But looks like it fails when XAMLC is applied. I have updated the code in the github sample.
Third - Yes, any control that inherits from View (be it be BoxView or Frame) can be used.
EDIT 2
As these commands (bindable properties) are of type ICommand, in order to Execute - you need to pass in a parameter. In case the command doesn't need a parameter - you can use null.
Recommended usage:
if(timerView.StopTimerCommand.CanExecute(null))
timerView.StopTimerCommand.Execute(null);

Resources