HyperlinkButton in C# XAMARIN.FORMS - c#

I want to create Label with click possibility like in WIN phone xaml
<HyperlinkButton Content="My Text to click"/>
Is there a possibility to do it in Xamarin.Forms?
I found this but is not the same:
https://github.com/XLabs/Xamarin-Forms-Labs/wiki/HyperLinkLabel

I'd take a much more standard approach and use a Button. Just set the background to match your app background and remove the border. Then there's no need for extra TapGestureRecongniser code. (Pseudo Code below:)
Xaml:
<Button Text="Click Me!" Background= "YourAppBackground" BorderWidth="0" Clicked="OnButtonClicked" />
Code-Behind:
void OnButtonClicked(object sender, EventArgs args)
{
//Open your link in here
}

I would suggest using GestureRecognizers and adding a Tap Gesture to a label. Ref: here
var label = new Label()
{
Text="My Hyperlink"
};
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => {
// handle the tap
};
label.GestureRecognizers.Add(tapGestureRecognizer);
GestureRecognizer is a public property on the View class which Label inherits from. See here

XAML code would be as follows:
<Label
Text="My Text to click"
HorizontalOptions="Center" >
<Label.GestureRecognizers>
<TapGestureRecognizer
Tapped="OnLabelTapped"
NumberOfTapsRequired="2" />
</Label.GestureRecognizers>
</Label>
Note: By default, NumberOfTapsRequired is 1.
Then in your .cs file, add the method OnLabelTapped.
public void OnLabelTapped(object sender, EventArgs args)
{
// Your code here
// Example:
// DisplayAlert("Message", "You clicked on the label", "OK");
}

Yes, you can either use Button Clicked or TapGestureRecognizer.
If you want to redirect to a site you can use WebView.
If you want to direct to your own Native page:
If you are using NavigationPage, you can use
Navigation.PushAsync(new Page());
If your not using NavigationPage and would like to change MainPage:
App.Current.MainPage = new MyContentPage();

This is a class I use to have a label act as a link:
public class SimpleLinkLabel : Label
{
public SimpleLinkLabel(Uri uri, string labelText = null)
{
Text = labelText ?? uri.ToString();
GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Device.OpenUri(uri)) });
}
}
For more options, this answer about creating a hyperlink in Xamarin Forms might be useful.

I do this --> create the following class:
public class ButtonAsLink : Button
{
public ButtonAsLink()
{
this.TextColor = Color.Blue;
this.BackgroundColor = Color.Transparent;
this.BorderWidth = 0;
}
}
Then everywhere you need to create a link button use this:
SendButton = new ButtonAsLink()
{
Text = "Send Logs...",
VerticalOptions = LayoutOptions.Center
};

If you want stylish the button (make it like hyperlink - with underline) you would like to implement the custom renderer:
Add this to xamarin.project
using Xamarin.Forms;
namespace xamarin.Mobile.Controls
{
public class HyperlinkButton : Button
{
public HyperlinkButton()
{
}
}
}
And implementation the renderer to IOS project:
using System.ComponentModel;
using xamarin.Mobile.IOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(xamarin.Mobile.Controls.HyperlinkButton), typeof(HyperlinkButtonRenderer))]
namespace xamarin.Mobile.IOS
{
public class HyperlinkButtonRenderer : ButtonRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control != null)
{
//Set attribute for underlineing information links
var underlineAttr = new UIStringAttributes { UnderlineStyle = NSUnderlineStyle.Single };
Control.SetAttributedTitle(new NSAttributedString(Control.CurrentTitle, underlineAttr), UIControlState.Normal);
}
}
}
}
I added renderer for iOS only. If you want to support another versions - you have to add renderers to this platforms.
And use it at xcml like this:
<ContentPage ...
xmlns:control="clr-namespace:xamarin.Mobile.Controls">
<control:HyperlinkButton Text="Cancel" Clicked="CancelClicked"/>
</ContentPage>

Update to KidCode answer with actual code for opening the browser link
Xaml View:
<Button Text="Go Google" Clicked="GoGoogle" />
Code behind:
void GoGoogle(object sender, EventArgs args)
{
Browser.OpenAsync("https://www.google.com");
}

Related

MahApps adding controlzex:ToolTipAssist.AutoMove programatically

I'm adding buttons to a Grid programatically like the code below in a MahApps Metro program. This works fine and the buttons are visible and clickable.
var tooltip = new ToolTip()
{
Content = "ToolTip Text"
};
var button = new Button()
{
Name = "Button1",
Focusable = false,
ToolTip = tooltip,
Content = "ClickMe"
};
button.Click += Button1_Click;
Grid.SetRow(button, 2);
Grid.SetColumn(button, 5);
MainGrid.Children.Add(button);
But I want to use the ToolTipAssist.AutoMove. In the designer you add it like this
<Button Name="Button1" Content="ClickMe">
<Button.ToolTip>
<ToolTip controlzex:ToolTipAssist.AutoMove="True" Content="ToolTip Text" />
</Button.ToolTip>
</Button>
But I haven't been able to add it in code. using ControlzEx; is present in the code. I've tried:
tooltip.controlzex //controlzex does not exist
tooltip.ToolTipAssist //ToolTipAssist does not exist
tooltip.AutoMove //AutoMove does not exist
So I'm thinking it has to be an event that has to be attached somehow, but which one?
The AutoMove property is an attached property, that exposes these methods:
public static bool GetAutoMove(ToolTip element) { //... }
public static void SetAutoMove(ToolTip element, bool value) { //... }
You set AutoMove like this to the tooltip in your code:
ToolTipAssist.SetAutoMove(tooltip, true);

How to change Fontawesome.wpf Icon in c# code

I'm fairly new to programming in wpf, so this might be pretty basic, but I have no Idea how to change a FontAwesome Icon of a button dynamically (in c# code). I use the nuget package as described in this post here. However the last part:
And finally in your C# code behind:
using FontAwesome.WPF; // on the top of the code
btnButton.Content = FontAwesomeIcon.LongArrowRight;
is not working for me, as it only shows the text "LongArrowRight" after clicking the button.
This is my code:
<Window
...
xmlns:fa="http://schemas.fontawesome.io/icons/">
<Grid>
<Button x:Name="btnPlay" Click="btnPlay_Click">
<Button.Content>
<fa:ImageAwesome Icon="Play"/>
</Button.Content>
</Button>
</Grid>
</Window>
using FontAwesome.WPF; // at the top
private bool running = false;
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
if (running)
{
running = false;
btnPlay.Content = FontAwesomeIcon.Play;
}
else
{
running = true;
btnPlay.Content = FontAwesomeIcon.Stop;
}
}
As already stated when the button is clicked it does not show the Icon but only the text "Stop" and when pressed again "Play".
FontAwesomeIcon is enum. When you assign enum value to Button.Content it will be displayed as text.
You need to assign ImageAwesome element to Content:
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.LongArrowRight };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Play };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Stop };

How to read image source or image name in xamarin.forms?

I am working on Xamarin forms, where I have used TapGestureRecognizer inside image now on tap of that image I need to get the source of the image in c#. How do I get that?. Why I am doing this is, radio buttons are not available in Xamarin forms, On tap of the image I will check the source of the image if the source is checked image then I need to change the source to unchecked and vice versa.
Here is my XAML code
<Image Scale="0.7" HorizontalOptions="Start" x:Name="radioButton" Source="unchecked.png">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="radioButton_Clicked">
</TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>
Here is my C# code
private void radioButton_Clicked(object sender, EventArgs e)
{
var imageSource = "";//get image source here
if (imageSource == "Checked.png")
{
radioButton.Source = "Unchecked.png";
}
else
{
radioButton.Source = "Checked.png";
}
}
you can achieve like this on radioButton_Clicked action
private void radioButton_Clicked(object sender, EventArgs e)
{
var imageSource = (Image)sender;//get image source here
var selectedImage = imageSource.Source as FileImageSource;
if (selectedImage.File == "Checked.png")
{
radioButton.Source = "Unchecked.png";
}
else
{
radioButton.Source = "Checked.png";
}
}
or you can use the custom plugin for support checked box refer this
https://github.com/XLabs/Xamarin-Forms-Labs
you can cast sender to image control
var imageSender = (Image)sender;
gestures

Change language for dialog after overriding language?

My code in MainPage.cs
ApplicationLanguages.PrimaryLanguageOverride = "ja-jp";
XAML
<Button content="Click" Click="Button_Click" />
after this i've opened dialog with my code
private async void Button_Click(object sender, RoutedEventArgs e)
{
{
testDialog dialog = new testDialog();
await dialog.ShowAsync();
}
}
My testDialog's XAML code
<TextBlock x:Uid="TestTextBlock" />
i've define the language's text in Resources.resw file, it worked fine if i put textblock in current MainPage but when i put it in dialog the textblock's text doesn't change, It only change after i reset the application. Any ideas how can i fix this guys ?'
Setting new language:
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = "ja-jp";
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
Reload Current page:
private bool Reload(object param = null)
{
var type = Frame.CurrentSourcePageType;
try
{
return Frame.Navigate(type, param);
}
finally
{
Frame.BackStack.Remove(Frame.BackStack.Last());
}
}
Also you can use Frame.Navigate(this.GetType()); for refreshing current page UI.
please take a look at this post for more information: Dynamically change the language of a universal app

How do i Use a PCL project to develop an app for Android and iOS in Xamarin?

I have created a Xamarin PCL project, it has Android iOS and Portable. I had a look at few examples, where in you can create a Login Page using Xaml and then validate those credentials using a CS file for it,but my question is lets say I validate those credentials, how do I jump from that UI page which is universal I suppose to the Android or the iOS part?
And where do I start ??
Sorry if I am being naive, I am new to Xamarin, any help would be appreciated.
This is the sample i'm referring for Portable,
using System;
using Xamarin.Forms;
namespace StoreCredentials
{
public class HomePageCS : ContentPage
{
public HomePageCS ()
{
var toolbarItem = new ToolbarItem {
Text = "Logout"
};
toolbarItem.Clicked += OnLogoutButtonClicked;
ToolbarItems.Add (toolbarItem);
Title = "Home Page";
Content = new StackLayout {
Children = {
new Label {
Text = "Main app content goes here",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
}
}
};
}
async void OnLogoutButtonClicked (object sender, EventArgs e)
{
DependencyService.Get<ICredentialsService> ().DeleteCredentials ();
Navigation.InsertPageBefore (new LoginPage (), this);
await Navigation.PopAsync ();
}
}
}
I would recommend you to read this before diving into Xamarin.
Also, this as it relates to something you are trying to do.

Categories

Resources