Get start position of a listview scroll to end in xamarin forms wpf - xamarin

I have worked on getting listview scroll position scroll to end in xamarin forms WPF application. I have tried below solution, it works in ios and android but unfortunately, it doesn't work in wpf application. Please suggest any idea to get scroll position of a listview end in xamarinforms WPF application.
Sample code you can find in below link
https://stackoverflow.com/questions/40373761/how-to-set-listview-to-start-showing-the-last-item-instead-in-xamarin-forms

If you're working with Xamarin Forms, you can create a control that extend from ListView and add methods for scrolling to top or bottom.
namespace YourAppName.Controls
{
public class CustomListView : ListView
{
public CustomListView() : this(ListViewCachingStrategy.RecycleElement)
{
}
public CustomListView(ListViewCachingStrategy cachingStrategy)
: base(cachingStrategy)
{
}
public void ScrollToFirst()
{
Device.BeginInvokeOnMainThread(() =>
{
try
{
if (ItemsSource != null && ItemsSource.Cast<object>().Count() > 0)
{
var firstItem = ItemsSource.Cast<object>().FirstOrDefault();
if (firstItem != null)
{
ScrollTo(firstItem, ScrollToPosition.Start, false);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
});
}
public void ScrollToLast()
{
try
{
if (ItemsSource != null && ItemsSource.Cast<object>().Count() > 0)
{
var lastItem = ItemsSource.Cast<object>().LastOrDefault();
if (lastItem != null)
{
ScrollTo(lastItem, ScrollToPosition.End, false);
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
}
And on your xaml:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:YourAppName.Controls"
x:Class="YourAppName.Views.CustomListViewPage">
<controls:CustomListView
x:Name="customListView"
ItemsSource="{Binding Items}"
SeparatorVisibility="None"
SelectionMode="None"
HasUnevenRows="true">
<controls:CustomListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label
FontSize="Medium"
Text="{Binding TestText}" />
</ViewCell>
</DataTemplate>
</controls:CustomListView.ItemTemplate>
</controls:CustomListView>
</ContentPage>
And on the code behind you can do something like this:
namespace YourAppName.Views
public partial class CustomListViewPage : ContentPage
{
public CustomListViewPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
this.customListView.ScrollToLast();
}
}

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);
}
}
}

How to prevent Editor to go behind the keyboard in Xamarin.Forms?

I have a Chat app. Currently, there is an Entry control for add chat text. Now I want to provide multiline Entry, same like Whatsapp.
If user type more than one line, it should automatic wrap the text to next line.
If user click on Nextline button in mobile keyboard, it should go to next line.
Height of Entry should be automatically increase upto 3 line and it should also decrease if user remove text.
To do that I have tried to replace Entry with Editor and implement following functionality.
1- Put an Editor in place of Entry.
2- Implement a functionality that keep keyboard open until user click on Message list screen or back button.
Now I am trying to implement auto height functioanlity but when user try to type, Editor goes behind the keyboard. Can anybody please suggest me how to keep Editor open and auto size?
Current code:
XAML:
<Grid x:Name="MessageControls" RowSpacing="1" ColumnSpacing="2" Padding="5"
Grid.Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<local:ChatEditorWithPlaceholder x:Name="txtMessage" Grid.Column="0" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
<Frame x:Name="SendButton" Grid.Column="1" Margin= "0" Padding="0" HasShadow="false" HeightRequest="25"
BackgroundColor="Transparent" HorizontalOptions="FillAndExpand">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="SendMessage_Click" NumberOfTapsRequired="1" />
</Frame.GestureRecognizers>
<Label Text="Send" x:Name="sendButton" TextColor="#1f88b7" HeightRequest="20"
HorizontalOptions="Center" VerticalOptions="Center"/>
</Frame>
</Grid>
Editor
public class ChatEditorWithPlaceholder : Editor
{
public ChatEditorWithPlaceholder()
{
this.TextChanged += (sender, e) => { this.InvalidateMeasure(); };
}
}
Editor Renderer:
public class ChatEditorRenderer : EditorRenderer
{
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if(Control != null) {
Control.ScrollEnabled = false;
}
var element = this.Element as ChatEditorWithPlaceholder;
Control.InputAccessoryView = null;
Control.ShouldEndEditing += DisableHidingKeyboard;
MessagingCenter.Subscribe<ConversationPage>(this, "FocusKeyboardStatus", (sender) =>
{
if (Control != null)
{
Control.ShouldEndEditing += EnableHidingKeyboard;
}
MessagingCenter.Unsubscribe<ConversationPage>(this, "FocusKeyboardStatus");
});
}
private bool DisableHidingKeyboard(UITextView textView)
{
return false;
}
private bool EnableHidingKeyboard(UITextView textView)
{
return true;
}
Screenshots:
Try this renderer for ios.
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly:ExportRenderer( typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace YourNameSpace.iOS
{
public class CustomEditorRenderer: EditorRenderer
{
public ChatEntryRenderer()
{
UIKeyboard.Notifications.ObserveWillShow ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0,0,0, args.FrameEnd.Height); //push the entry up to keyboard height when keyboard is activated
}
});
UIKeyboard.Notifications.ObserveWillHide ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
});
}
}
}
for android add this in MainActivity
App.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().
UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
For Ios there is one plugin. You can use that. The link is Here.
For Andorid you have to just set below code in MainActivity after LoadApplication(new App()) method.
App.Current.On<Xamarin.Forms.PlatformConfiguration.Android().
UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
Updated answer for iOS :
For IOS you can use the following custom renderer to solve the keyboard overlapping issue. And please removed the keyboardoverlap nuget package from the project.
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using HBIClientFacingApp;
using HBIClientFacingApp.iOS;
[assembly:ExportRenderer( typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace YourNameSpace.iOS
{
public class CustomEditorRenderer: EditorRenderer
{
public ChatEntryRenderer()
{
UIKeyboard.Notifications.ObserveWillShow ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0,0,0, args.FrameEnd.Height); //push the entry up to keyboard height when keyboard is activated
}
});
UIKeyboard.Notifications.ObserveWillHide ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
});
}
}
}
You can try to change this line:
<local:ChatEditorWithPlaceholder x:Name="txtMessage" Grid.Column="0" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
For this one:
<Editor x:Name="txtMessage" Grid.Column="0" AutoSize="TextChanges" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>

Xamarin Forms ListView text not displayed

I'm new to Xamarin Forms, I'm following the official tutorial for learning Xamarin forms. While learning about navigation using Phoneword project of the following link
https://developer.xamarin.com/guides/xamarin-forms/getting-started/hello-xamarin-forms-multiscreen/quickstart/
The listview text is not appearing. Please help me!
CallHistoryPage.xaml: Here the listview is there.
<?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:local="clr-namespace:App1;assembly=App1"
x:Class="App1.CallHistoryPage"
Title="Call History">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="20, 40, 20, 20"/>
<On Platform="Android" Value="20"/>
</OnPlatform>
</ContentPage.Padding>
<StackLayout>
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs: SourceItem values are updated in this class.
namespace App1
{
public partial class MainPage : ContentPage
{
string translatedNumber;
public MainPage()
{
InitializeComponent();
}
void OnTranslate(object sender, EventArgs e)
{
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (!string.IsNullOrWhiteSpace(translatedNumber))
{
callButton.IsEnabled = true;
callButton.Text = "Call " + translatedNumber;
}
else
{
callButton.IsEnabled = false;
callButton.Text = "Call";
}
}
async void OnCall(object sender, EventArgs e)
{
if (await this.DisplayAlert(
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No"))
{
var dialer = DependencyService.Get<IDialer>();
if (dialer != null)
{
App.PhoneNumbers.Add(translatedNumber);
callHistoryButton.IsEnabled = true;
dialer.Dial(translatedNumber);
}
}
}
async void OnCallHistory(object sender, EventArgs e)
{
await Navigation.PushAsync(new CallHistoryPage());
}
}
}
App.xaml.cs: Sourceitem for listview is in this class
namespace App1
{
public partial class App : Application
{
public static IList<string> PhoneNumbers { get; set; }
public App()
{
InitializeComponent();
PhoneNumbers = new List<string>();
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
For more details please follow the link added above. Same tutorial is followed.
You forgot to 'tell' ListView what to display.
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
creates a ListView with empty cells, hence they are not displaying anything. You'll have to set the ListView.ItemTemplate in order to display anything
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding .}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The BindingContext within the DataTemplate will be the respective item from App.PhoneNumbers. Since the items are bare strings we bind to ., which refers to the bound element itself.
See here for ListViews in Xamarin.Forms.
You have not added any numbers in PhoneNumbers list. Add number first in PhoneNumbers list and then check.
public App()
{
InitializeComponent();
PhoneNumbers = new List<string>();
PhoneNumbers.Add("123456789");
PhoneNumbers.Add("178967897");
PhoneNumbers.Add("178945678");
MainPage = new NavigationPage(new MainPage());
}
I think you have forget to take input from user.So add this line in OnCall method
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
Try this,
async void OnCall(object sender, EventArgs e)
{
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (await this.DisplayAlert(
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No"))
{
var dialer = DependencyService.Get<IDialer>();
if (dialer != null)
{
App.PhoneNumbers.Add(translatedNumber);
callHistoryButton.IsEnabled = true;
dialer.Dial(translatedNumber);
}
}
}

How to underline label with underline effect in Xamarin Forms?

I followed this tutorial to create underline effect. However, when my page starts it breaks without exception being caught. Has anyone managed to create underline effect? Here is a code:
UnderlineEffect.cs:
namespace XX.CustomForms
{
public class UnderlineEffect : RoutingEffect
{
public const string EffectNamespace = "XX.CustomForms";
public UnderlineEffect() : base($"{EffectNamespace}.{nameof(UnderlineEffect)}")
{
}
}
}
UnderlineLabel_Droid.cs:
[assembly: ResolutionGroupName(UnderlineEffect.EffectNamespace)]
[assembly: ExportEffect(typeof(UnderlineEffect), nameof(UnderlineEffect))]
namespace XX.Droid.Renderers
{
public class UnderlineEffect : PlatformEffect
{
protected override void OnAttached()
{
SetUnderline(true);
}
protected override void OnDetached()
{
SetUnderline(false);
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
if (args.PropertyName == Label.TextProperty.PropertyName || args.PropertyName == Label.FormattedTextProperty.PropertyName)
{
SetUnderline(true);
}
}
private void SetUnderline(bool underlined)
{
try
{
var textView = (TextView)Control;
if (underlined)
{
textView.PaintFlags |= PaintFlags.UnderlineText;
}
else
{
textView.PaintFlags &= ~PaintFlags.UnderlineText;
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot underline Label. Error: ", ex.Message);
}
}
}
}
And my xaml:
xmlns:custom="clr-namespace:XX.CustomForms;assembly=XX"
<Label Text="Privacy Notice" HorizontalTextAlignment="Center" >
<Label.Effects>
<custom:UnderlineEffect />
</Label.Effects>
</Label>
Xamarin Forms added a TextDecorations property to Labels. Update to Xamarin Forms 3.3.0+ and just set:
C#
Label label = new Label {
TextDecorations = TextDecorations.Underline
}
XAML
<Label TextDecorations="Underline"/>
Docs Link
Be aware that there was a bug on iOS when an underlined Label is in a ListView. Looks like it has been fixed and released in 3.5.0. I am still using a custom renderer on iOS for now until I am ready to update to the latest version.
GitHub issue
So continue using the iOS effect if you have not updated to XF 3.5.0 yet.
The lengths some people are going to to get underlined text in Xamarin is insane. Here's a way to do it without a thousand line custom renderer. The negative margin trick came from this guy.
<StackLayout HorizontalOptions="Start">
<Label Text="Underlined Text" />
<BoxView HeightRequest="1" BackgroundColor="Purple" HorizontalOptions="FillAndExpand" Margin="0,-7,0,0" />
</StackLayout>
Use TextDecorations property in Label class.
<Label Text="Underlined Text" TextDecorations="Underline"/>
To be able to add an underline to a label, we created custom renderers that inherits from Label.
public class CustomLabel : Label
{
public static readonly BindableProperty IsUnderlinedProperty = BindableProperty.Create("IsUnderlined", typeof(bool), typeof(CustomLabel), false);
public bool IsUnderlined
{
get { return (bool) GetValue(IsUnderlinedProperty); }
set { SetValue(IsUnderlinedProperty, value); }
}
}
In your xaml page you can use it as:
<s:CustomLabel IsUnderlined="True" Text="UnderlinedText" FontSize="18" HorizontalOptions="CenterAndExpand">
Note that s is the namespace declared in the root element of xaml page.
Now your renderer in Android would be something like that:
public class CustomLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null && Element != null)
{
if (((CustomLabel)Element).IsUnderlined)
{
Control.PaintFlags = PaintFlags.UnderlineText;
}
}
}
}

System.NullReferenceException Xamarin Maps

I'm getting a NullException when will display the map, but can not detect;
I tried to change the name of the maps, locazation, etc., but without success.
You may be able to identify where is my mistake, please help me!
public partial class LocationPage : ContentPage
{
public Clinica _clinica;
public LocationPage(Clinica clinica)
{
InitializeComponent();
Clinica = clinica;
SetupMap();
}
public Clinica Clinica
{
get
{
return _clinica;
}
set
{
_clinica = value;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
// Typically, is preferable to call into the viewmodel for OnAppearing() logic to be performed,
// but we're not doing that in this case because we need to interact with the Xamarin.Forms.Map property on this Page.
// In the future, the Map type and it's properties may get more binding support, so that the map setup can be omitted from code-behind.
SetupMap();
}
void SetupMap()
{
if (Device.OS != TargetPlatform.WinPhone && Device.OS != TargetPlatform.Windows)
{
var pin = new Pin()
{
Type = PinType.Place,
Position = new Position(Clinica.Latitude, Clinica.Longitude),
Label = Clinica.Nome
};
clinicaMap.Pins.Clear();
clinicaMap.Pins.Add(pin);
clinicaMap.MoveToRegion(MapSpan.FromCenterAndRadius(pin.Position, Distance.FromMiles(10)));
}
}
}
}
LocationPage.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:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
x:Class="CartaoDeTodos.View.LocationPage">
<StackLayout>
<maps:Map x:Name="clinicaMap"
VerticalOptions="FillAndExpand"/>
</StackLayout>
</ContentPage>

Resources