Change language for dialog after overriding language? - c#

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

Related

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

Xamarin Picker showing undesirable elements on UI

Pulling my hair out at the point. My Picker is showing an annoying line on the UI and/or the Picker's Title property if that's enabled. I simply want the Picker, not the stuff showing on the UI beneath it. Any idea on how to achieve this? Do I have to use a custom renderer or is there something simple I'm missing?
Note: The list is intentionally empty in the below examples.
Without the title, I click the Existing button, the line shows, click it again and the modal appears:
With the title, I click the Existing button, the line and title show, click it again and the modal appears:
Don't know why I have to click the button twice. But it's only on the initial page load. If I exit the modal and click the button again, it immediately appears, no double-click. Not sure if that's related to my original question, but thought I'd include it for additional information.
NewSubjectPage.xaml (chopped for brevity)
<ContentPage.Content>
<StackLayout x:Name="NewSubjectMainLay">
<ScrollView>
<StackLayout x:Name="NewSubjectChildLay">
<Grid>
<Button
x:Name="NewSubjectExisChrtBtn"
Clicked="NewSubjectExisChrtBtn_Clicked"
Grid.Column="2"
Text="Existing" />
</Grid>
</StackLayout>
</ScrollView>
<Picker
x:Name="NewSubjectExisChrtPck"
IsVisible="False"
ItemsSource="{Binding Charts}"
ItemDisplayBinding="{Binding Name}"
SelectedIndexChanged="NewSubjectExisChrtPck_SelectedIndexChanged"
Title="Select chart"
Unfocused="NewSubjectExisChrtPck_Unfocused"/>
</StackLayout>
</ContentPage.Content>
NewSubjectPage.xaml.cs (chopped for brevity)
public partial class NewSubjectPage : ContentPage
{
private string chartName;
private readonly NewSubjectViewModel _viewModel;
public string ChartName
{
get => chartName;
private set
{
chartName = value;
OnPropertyChanged();
}
}
public NewSubjectPage()
{
InitializeComponent();
BindingContext = _viewModel = new NewSubjectViewModel();
chartName = "";
}
private void NewSubjectExisChrtBtn_Clicked(object sender, EventArgs e)
{
_viewModel.LoadChartsCommand.Execute(null);
NewSubjectExisChrtPck.IsVisible = true;
NewSubjectExisChrtPck.Focus();
}
private void NewSubjectExisChrtPck_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
int selectedIndex = picker.SelectedIndex;
if (selectedIndex != -1)
{
ChartName = picker.Items[picker.SelectedIndex];
}
}
private void NewSubjectExisChrtPck_Unfocused(object sender, FocusEventArgs e)
{
NewSubjectExisChrtPck.IsVisible = false;
NewSubjectExisChrtPck.Unfocus();
}
}
NewSubjectViewModel.cs (chopped for brevity)
class NewSubjectViewModel : BaseViewModel
{
private ObservableCollection<Chart> charts;
public ObservableCollection<Chart> Charts
{
get { return charts; }
private set
{
charts = value;
OnPropertyChanged();
}
}
public Command LoadChartsCommand { get; set; }
public NewSubjectViewModel()
{
LoadChartsCommand =
new Command(
async () => await ExecuteLoadChartsCommand()
);
}
private async Task ExecuteLoadChartsCommand()
{
try
{
IndicatorRunning = true;
var list = await App.Database.GetChartsAsync();
Charts = new ObservableCollection<Chart>(list);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
Thanks for your help! Let me know if you need to see anything else.
First, I was not able to reproduce the issue of the modal not showing until a second click of the button. You might need to provide more code for that to happen. To even use your code sample I had to replace var list = await App.Database.GetChartsAsync(); with something else to simulate a long running task that returns an empty list. Also had to create a Chart type with a Name property. Not to mention BaseViewModel. In the future, please provide all code to reproduce the issue so there is minimal work required of the person who is trying to help you. There is concept on Stack Overflow called the MCVE (minimal, complete, verifiable example): http://stackoverflow.com/help/mcve
That said, perhaps the first click is actually focusing the emulator and making it the active app, and then the second is the first actual click on the button? This I can reproduce. IOW, if the emulator is not the foreground app, you have to click it once to make it active and then your app will handle clicks.
As for the undesirable UI, you do realize that the Picker UI is basically a clickable label that when clicked displays the actual picker modal? So when you make it visible, what you are making visible is the label UI, which has the line and the Title (if set), and when you focus that label, then the actual picker dialog is displayed. If you don't want to see the UI Label at all, then why make it visible? You can focus it without making it visible, so just remove the line NewSubjectExisChrtPck.IsVisible = true;
As a side note, when you call _viewModel.LoadChartsCommand.Execute(null); that calls an async method, var list = await App.Database.GetChartsAsync(); , so the LoadChartsCommand returns before you set the Charts property, and also then the code following the call to _viewModel.LoadChartsCommand.Execute(null); also executes before LoadChartsCommand really finishes, so you are making the picker visible and focusing it before the LoadChartsCommand finishes as well, so if you were loading actual items for the picker to display, they may not be there the first time. Maybe it's just the sample code, but I see no reason to use a command here, but rather you should just call an awaitable task. You are not binding to the LoadChartsCommand, so I see no reason for you to even use a Command in this scenario. Instead I suggest making ExecuteLoadChartsCommand public and calling it directly, e.g.:
private async void NewSubjectExisChrtBtn_Clicked(object sender, EventArgs e)
{
//_viewModel.LoadChartsCommand.Execute(null); // Returns immediately, so picker not loaded with items yet.
await _viewModel.ExecuteLoadChartsCommand(); // Waits for method to finish before before presenting the picker.
//NewSubjectExisChrtPck.IsVisible = true;
NewSubjectExisChrtPck.Focus();
}

Changing a color of a icon from an action on an other page

I am a beginner on C#, I am coding an UWP app on Visual Studio, mostly for Windows 10 platforms.
Here's my problem:
I have a navigation view on the main page, which lists a few subjects.
Clicking on one of them brings you to a page (Page1) where I have radio buttons, that changes the color of the title of this Page1.
I would like to have this color applied to the subject on the main page
Can't figure out how to do...
Any tips?
Thanks!
You can access the NavigationView in MainPage.xaml.cs by creating a static instance of MainPage and change the color.
Here is the solution:
MainPage.xaml
<NavigationView x:Name="nvSample"
x:FieldModifier="Public">
...
</NavigationView>
MainPage.xaml.cs
public static MainPage Current;
public MainPage()
{
this.InitializeComponent();
Current = this;
}
Page1.xaml.cs
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
var nav = MainPage.Current.nvSample;
nav.Foreground = new SolidColorBrush(Colors.Yellow);
}
Best regards.
Thank you very much Richard, I made it :)
The Page1.xaml.cs code changed all the texts foreground in my page though, so I used this:
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
RadioButton radio = (RadioButton)sender;
{}
if (radio != null)
{
String selected = radio.Tag.ToString();
switch (selected)
{
default:
case "Red":
Title.Foreground = new SolidColorBrush(Colors.Red);
MainPage.Current.Subject1.Foreground = new SolidColorBrush(Colors.Red);
break;`
Thank you again.
Now next mission for me, saving those colors after the application is closed so they stay the same when the app is lunched. If you have any advices... :)

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

HyperlinkButton in C# XAMARIN.FORMS

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

Categories

Resources