More convenient way to localize in windows phone apps - windows-phone-7

Currently, if you want to localize say Application Title in a windows phone app you would do this:
<TextBlock Text="{Binding LocalizedResources.ApplicationTitle,
Source={StaticResource LocalizedStrings}}" />
This is too long, and certain parts are repeated for each binding. Even if you were to rename LocalizedResources property to R and LocalizedStrings class to LS for example, some repetition still exist.
So I tried making a class that inherits from Binding class and implemented as follows:
public class LocalizedBinding : Binding {
public LocalizedBinding(string path) : base(path) {
Source = Application.Current.Resources["LocalizedStrings"];
}
}
The hope was to use it as follows:
<TextBlock Text="{b:LocalizedBinding LocalizedResources.ApplicationTitle}" />
However, the app crashes immediately upon start and I can't see any errors even in debugger. Any tips on how this might work?
Thanks
Edit:
Adding a parameterless constructor to LocalizedBinding and appending Path= to the binding fixes it.

This is fixed by adding a parameterless constructor to the LocalizedBinding class
public class LocalizedBinding : Binding {
public LocalizedBinding() {
Source = Application.Current.Resources["LocalizedStrings"];
}
public LocalizedBinding(string path) : base(path) {
Source = Application.Current.Resources["LocalizedStrings"];
}
}

You might try and put a Localization class into your App.xaml, then on Application_Launching check which language the user has set. Everywhere that you display the text you then refer to the App.xaml class.

Related

Databinding Entry in Xamarin Forms

I'm trying to capture the value of the entry in a Login text box in Xamarin Forms. I've created the class, data bound in xmal, but running into build errors when compiling for iOS. Any pointers much appreciated.
Login.xmal:
<Entry x:Name="{Binding Source = AppLoginUsername;}" Placeholder="Username"
Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"
HorizontalOptions="StartAndExpand" WidthRequest="300" />
FormEntry Class.cs
using System;
namespace SGC.Class
{
public class FormEntryBindings
{
public FormEntryBindings()
{
}
public static string AppLoginUserName { get; set; }
}
}
Home.cs (Grabs the username entered in Login page and figures out the CustomerID)
private async void getCustBalance()
{
HttpClient client = new HttpClient();
string x = FormEntryBindings.AppLoginUserName;
int custid = GetCustomerId(x);
The errors are:
Invalid token '{' in class, struct, or interface member declaration
Invalid expression term '='
Type or namespace definition, or end-of-file expected
Why dont you just give it a name, and bind the text?
Eg
x:Name=“User” Text=“{Binding AppLoginUsername}”...
Well, based on the comments, I think your problem is that you can get the AppLoginUserName in the login page, however,you want use the AppLoginUserName in another page(another view).
I would give your several suggestions:
1.You can pass the value to the page where you want to use.
2.Use Xamarin.Essentials: Preferences.
You can save the AppLoginUserName once the user has logged in:
using Xamarin.Essentials;
Preferences.Set("AppLoginUserName", "value");
At another view where you want to use, you can get the value:
var myValue = Preferences.Get("AppLoginUserName", "default_value");
And remove the key from preferences when the user has logged out or under other situation:
Preferences.Remove("my_key");
You can refer:essentials/preferences
You can’t bind the name. Name is something that generates the code and you can’t change the name of the variable on the fly.

Mvvmcross: Text format binding with MvxLang

I am building a native Xamarin app, and I am using Mvvmcross to do it. It is a really nice tool but I am still learning about how it works.
I found in the documentation yould could do the following thing with binding:
local:MvxBind="Text Format('Line: {0}', Line.Name)"
Here your binding the Testclass.Name variable with the format, so the result will be
Line: TestName
Now I want to do the same thing but also taking in a count the translation for Line:. So normally for translation you do the following.
local:MvxLang="Text Line_Label"
So my idea was to do something like this:
local:MvxLang="Text Format('{0}{1}', Line_Label, Line.Name)"
But it doesn't work like this. Does anybody have an idea if this is possible yet and how?
Use Tibet binding with local:MvxBind. Let's assume, that you have:
BaseViewModel.cs
public abstract class BaseViewModel : MvxViewModel
{
public IMvxLanguageBinder TextSource
{
get
{
return new MvxLanguageBinder(
Constants.GeneralNamespace,
GetType().Name);
}
}
}
MainViewModel.cs inheriting from BaseViewModel, with string property Name:
public string Name => "Radek";
TextProviderBuilder like in Stuart's N+1 days (no. 21) https://www.youtube.com/watch?v=VkxHtbJ_Tlk
JSON translation file with "MyLabel" key
{
"MyLabel" : "Your name:"
}
Answer: Then Android layout axml file will contain binding
local:MvxBind="Text Language(TextSource,'MyLabel') + ' ' + Name; Click NextCommand"
I don't know how to do this with local:MvxLang but the code above does the job :)

Using self created dll in Xamarin.Forms showing white screen on device

I am trying to create and use a DLL in Xamarin.Forms Project. This is given in the Charles Petzold's book 'Creating Mobile Apps using Xamarin.Form'.
It gives the following method to access the library that I have created
"From the PCL project of your application solution, add a reference to the library PCL assembly which is the dynamic-link library generated from the library project"
My library project is this
FILE: HslColorExtension.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Xamarin.FormsBook.Toolkit
{
public static class Toolkit
{
public static void Init()
{
}
}
public class HslColorExtension : IMarkupExtension
{
public HslColorExtension()
{
}
public double H { set; get; }
public double S { set; get; }
public double L { set; get; }
public double A { set; get; }
public object ProvideValue(IServiceProvider servicePRovider)
{
return Color.FromHsla(H, S, L, A);
}
}
}
THE actual project is CustomExtensionDemo
In that the MainPage.xaml is
<?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:toolkit="clr-namespace:Xamarin.FormsBook.Toolkit;assemby=Xamarin.FormsBook.Toolkit"
x:Class="CustomExtensionDemo.MainPage">
<StackLayout>
<Label Text="UTKARSH">
<Label.BackgroundColor>
<toolkit:HslColorExtension H="0" S="1" L="0.5"/>
</Label.BackgroundColor>
</Label>
</StackLayout>
</ContentPage>
THE METHOD HOW I ADDED THE DLL TO THE APPLICATION
FROM THE LIBRARY IS TOOK THE PATH THAT GENERATED THE DLL
C:\Users\admin\Desktop\Xamarin.FormsBook.Toolkit\Xamarin.FormsBook.Toolkit\obj\Debug
The name of the DLL is
Xamarin.FormsBook.Toolkit.dll
I added the reference to the actual project. browsed the path to
C:\Users\admin\Desktop\Xamarin.FormsBook.Toolkit\Xamarin.FormsBook.Toolkit\obj\Debug
and added the DLL : Xamarin.FormsBook.Toolkit.dll
Everything compiled correctly But I am getting a complete white screen on the Android Phone I am having .
POINTS:
1. I have set MainPage.xaml as the MainPage in the App.xaml.cs.. I have tried to put Label without the property element syntax and that worked.
I have not checked on iOS I think that there it would have the same problem as the problem could be in method of using the DLL in the application.
IDE:VS 2017
THE ERROR THAT IS DISCUSSED IN THE BELOW DISCUSSION
NOW I REQUIRE SOME WAY TO REMOVE THE "Windows Phone Silverlight 8.1" AND IT DOES NOT GIVE OPTION TO REMOVE THAT.
I'm fairly certain your problem is incompatible targets of your PCL.
Instead of adding the reference by browsing for the DLL, add it by selecting the project. This approach will check for compatibility of the DLL. Most likely you will need to change targets, fool around with nuget, etc.
Secondly I would recommend that your first platform for testing be UWP. There seems to be much better diagnostics on UWP. When I tried your code, I got the white screen on Android, but when using UWP as a platform I got an exception that said the HslColorExtension could not be found in the DLL.
If you follow these steps it should work for you:
You mis-spelled assembly as "assemby" in your XAML.
xmlns:toolkit="clr-namespace:Xamarin.FormsBook.Toolkit;assemby=Xamarin.FormsBook.Toolkit"
To make sure we're starting clean, let's just create a fresh Xamarin.FormsBook.Toolkit project and get rid of the one you've been using:
a) Copy out the code that you've already written so you don't lose it.
b) Create a new Xamarin.FormsBook.Toolkit project and only target those platforms that you would feasibly use this toolkit in. For example you would never use this in Silverlight because you're going to be referencing IMarkupExtension which is specific to Xamarin Forms.
c) Add a reference to your Toolkit project from your Xamarin Forms PCL project (looks like you're calling that "CustomExtensionDemo"). Don't reference the .dll but rather the project itself. This will spare you other headaches down the road.
d) Copy your HslColorExtension file (and any other classes you have) back in to the new project.
e) Add the Xamarin.Forms Nuget package to your Xamarin.FormsBook.Toolkit PCL, and a "using Xamarin.Forms" line at the top of your HslColorExtension file so that it recognizes the IMarkupExtension interface.
Add an empty Init function (or call it whatever you want) to your HslColorExtension class and then call it from your App.xaml.cs. This has the effect of "waking the compiler/linker up" to the fact that you have an assembly reference in XAML, since XAML is loaded at runtime. It does seem a bit hokey to have to do this, but you can tuck away that ugliness in your App.xaml.cs and you never have to see it again. If you're curious and want to see what's going on, try running it both with and without the call to Init, and take a look at your Android project's bin/Debug folder. When you call Init you'll see your Xamarin.FormsBook.Toolkit.dll appear in that folder. When you don't call Init it doesn't pull your assembly in. That's the core issue here.
Your resulting markup extension code would look like this:
public class HslColorExtension : IMarkupExtension
{
public static void Init()
{
}
public double H { set; get; }
public double S { set; get; }
public double L { set; get; }
public double A { set; get; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return Color.FromHsla(H, S, L, A);
}
}
And your App.xaml.cs like this:
public partial class App : Application
{
public App()
{
HslColorExtension.Init();
InitializeComponent();
MainPage = new MainPage();
}
...
}
If that doesn't solve it for you, let me know! :-)

UWP - Inherit from Base Page C#

I'm one of the many windows app developers. I'm sure someone other ran in this problem too. I want to have a base page (c#) where I add methods and use it in some pages without coding it over and over.
I've tried it like this:
Basicpage.cs:
public class BasicPage : Page
{
public void Test() {
}
}
SettingsPage.xaml.cs:
public sealed partial class SettingsPage : BasicPage{
public SettingsPage () {
InitializeComponent();
}
}
On the bold "BasicPage" there are the errors:
Base class of "...SettingsPage" differs from declared in other parts
and
Base type 'BasicPage' is already specified in other parts
Does someone know a solution?
I assume SettingsPage has a XAML part, which also needs to be derived from BasicPage:
<local:BasicPage x:Class="MyNamespace.SettingsPage" ...>
<!-- settings page content -->
</local:BasicPage>

Windows Phone inherited application page: designer error but compiles

I have a XAML Page which inherits from a userdefined class of mine:
<xpap:GenericListPage
x:Class="my.View.ListPage"
xmlns:xpap="clr-namespace:my.View.Generic" ... />
Initially I wanted to use a generic base class for my XAML page, but that was no possible (at least in WP7; is it possible in WP8 to use generic base classes for pages?). So I ended up with this work-around (ExtendedPhoneApplicationPage inherits from PhoneApplicationPage adds extra functionality/behaviour that all my pages like ListPage etc. should have in commen):
namespace my.View
{
namespace Generic
{
public partial class GenericListPage :
ExtendedPhoneApplicationPage<ListViewModel>
{
...
}
}
public partial class ListPage : Generic.GenericListPage
{
...
}
public class ExtendedPhoneApplicationPage<T> :
PhoneApplicationPage where T : class, IViewModelBase
{
...
}
}
This worked fine all together until I installed the WP8 SDK (as far as I can remember). The designer says "invalid markup" and there is an error saying: "The name "GenericListPage" does not exist in the namespace "clr-namespace:my.View.Generic"."
The strange part is, that the solution compiles and can be deployed on the emulator. Anyone know why or how to eliminate the error?

Resources