I have a problem with localization of Silverlight application using resources. I wanted to make my multilingual mechanizm to be cross platform thats why I placed all localizable resources in project of type Portable Class Library.
In this project I created two resource files
Localization.resx and Localization.en.resx and I set and "access modifier" to public in both files. Then I created the proxy class called "LocalizationProxy" which is a proxy class to enable bindings.
public class LocalizationProxy : INotifyPropertyChanged
{
public Localization LocalizationManager { get; private set; }
public LocalizationProxy()
{
LocalizationManager = new Localization();
}
public void ResetResources()
{
OnPropertyChanged(() => LocalizationManager);
}
#region INotifyPropertyChanged region
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged<T>(Expression<Func<T>> selector)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(GetPropertyNameFromExpression(selector)));
}
}
public static string GetPropertyNameFromExpression<T>(Expression<Func<T>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
{
memberExpression = (MemberExpression)lambda.Body;
}
return memberExpression.Member.Name;
}
#endregion
}
In the next step I modifed Silverlight csproj file and added "en" culture to supported types
<SupportedCultures>en</SupportedCultures>
Furthermore in application resources I created and instance of LocalizationProxy class
<Application.Resources>
<Localization:LocalizationProxy x:Key="LocalizationProxy"></Localization:LocalizationProxy>
</Application.Resources>
I also changed "Neutral Language" in Assembly Information to "Polish" - this should be default application language. In the last step I bouned some values from view to the resources
<TextBlock TextWrapping="Wrap" x:Name="PageTitle" Text="{Binding Source={StaticResource LocalizationProxy},Path=LocalizationManager.Title,Mode=TwoWay}" />
Unfortunatelly despite the fact that Thread.CurrentThread.CurrentCulture is "pl-PL" my application is still in English language.However if I use the same code in Windows Phone application everything works fine - I can even change application language in runtime. Is there any difference in localizing Silverlight application and localizing Windows Phone apps ?
Here is my application
http://www.fileserve.com/file/TkQkAhV/LocalizationSolution.rar
As I mentioned before, Localization in Windows Phone works fine, but in Silverlight application labels are not translated
You should use the fully qualified ISO 3166 and 639 codes combined with a hyphen as Rumplin describes.
see
http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
http://en.wikipedia.org/wiki/ISO_3166-1
make sure you made all the steps bellow properly.
Create your ViewModel Class
Implement the INotifyPropertyChanged interface:
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Create the property that will return the right language:
public object MainResourcesSmart
{
get
{
var myCulture = Thread.CurrentThread.CurrentUICulture.Name.ToUpper();
switch (myCulture)
{
case "EN-US":
return new MyResourceEn();
case "ES-AR":
return new MyResourceEs();
default:
return new MyResource();
}
}
}
Set all resources to public
Use the method bellow to refresh it on screen every time you change the language:
private void MainResourcesSmartRefresh()
{
OnPropertyChanged("MainResourcesSmart");
}
Bind the ViewModel to your View (MainPage) for example:
public MyViewModel ViewModel
{
get { return (MyViewModel)DataContext; }
set { DataContext = value; }
}
public MainPage()
{
ViewModel = new MyViewModel();
}
Bind the Resouce property to your UserControl like:
<TextBlock Height="20" HorizontalAlignment="Left" VerticalAlignment="Bottom" Foreground="#7F4F8AB2" FontSize="10.667" Text="{Binding MainResourcesSmart.NameOfTheCompany}" FontFamily="Trebuchet MS" />
Related
Context: I am handed this massive enterprise iOS & Android Xamarin Native applications that doesn't use ViewModels or any MVVM framework. It does have a separated Network services layer and it has a lot of pages, so starting over won't make any sense.
Why the change is needed: No MVVM, the services layer is called directly from the UI classes (Fragments & ViewControllers), and there is no good abstraction. So I will start with 1 view and then create TechDebt to transform the rest of the app.
What I know:
Adding MVVM frameworks require creating extensive changes, especially to use Navigation services for Navigating the views, and are best done if added when green-fielding the application.
As seen here, Android has an easy way of using a ViewModel but I won't be able to use that for iOS then.
I also know that I can launch a Xamarin Forms page instead and that will be all ready for MVVM, since I can just assign the BindingContext property to an instance of the ViewModel.
What I need: I need to create one new page for iOS & one for Android. I want to be able to create a ViewModel that's shared between iOS & Android. I want to be able to use it for a single view that I am creating and it should be initialized when the page is loaded.
How can I add 1 viewmodel that's shared by a ViewController & a Fragment? Am I missing something, is it much easier than I am making it?
Ended up being able to use MvvmLight for this. Added the Nuget package to the projects, Created a ViewModelBase in the Core Shared Library Project:
public abstract class ViewModelBase : GalaSoft.MvvmLight.ViewModelBase
{
private PropertyChangedEventHandler propertyChangedEventHandler;
protected bool IsLoading { get; set; }
public bool RegisteredPropertyEventHandler { get; set; }
public const string ErrorMessagePropertyName = "ErrorMessage";
public string ErrorMessage { get; set; }
public string SuccessMessage { get; set; }
public void RegisterPropertyEventHandler(PropertyChangedEventHandler propertyChangedEventHandler)
{
this.propertyChangedEventHandler = propertyChangedEventHandler;
this.PropertyChanged += propertyChangedEventHandler;
this.RegisteredPropertyEventHandler = true;
}
public void UnegisterPropertyEventHandler()
{
if (this.RegisteredPropertyEventHandler)
{
this.PropertyChanged -= propertyChangedEventHandler;
this.RegisteredPropertyEventHandler = false;
this.propertyChangedEventHandler = null;
}
}
public void TearDown()
{
this.UnegisterPropertyEventHandler();
}
protected void NotifyError (string message)
{
this.ErrorMessage = message;
RaisePropertyChanged (() => ErrorMessage);
}
}
and a ViewModelLocator
public class ViewModelLocator
{
public const string ABCPageKey = "ABCPage";
public ABCViewModel ABC
{
get
{
return ServiceLocator.Current.GetInstance<ABCViewModel> ();
}
}
public ViewModelLocator ()
{
ServiceLocator.SetLocatorProvider (() => SimpleIoc.Default);
// Register all of the view models
SimpleIoc.Default.Register<ABCViewModel> ();
}
public static void Cleanup ()
{
}
public T GetViewModel<T> ()
{
return ServiceLocator.Current.GetInstance<T> ();
}
}
On the iOS side, I already had a BaseUIViewController, so I created a BaseViewModelUIViewController on top of it
public abstract partial class BaseViewModelUIViewController<T> : BaseUIViewController where T : ViewModelBase
{
public T ViewModel
{
get
{
return App.Locator.GetViewModel<T> ();
}
}
public BaseViewModelUIViewController (IntPtr handle) : base (handle)
{
}
internal virtual void ViewModelPropertyChangedHandler (object sender, PropertyChangedEventArgs e)
{
Console.WriteLine (string.Format ("****** Property Changed for {0} in {1}", e.PropertyName, this.GetType ().Name));
switch (e.PropertyName)
{
default:
break;
}
}
}
And then Android, similarly I already had a BaseFragment, so I created a BaseViewModelFragment on top of it
public class BaseViewModelFragment<T> : BaseFragment where T : ViewModelBase
{
public T ViewModel
{
get
{
return App.Locator.GetViewModel<T> ();
}
}
public BaseViewModelFragment (string title) : base (title)
{
}
internal virtual void ViewModelPropertyChangedHandler (object sender, PropertyChangedEventArgs e)
{
Console.WriteLine (string.Format ("****** Property Changed for {0} in {1}", e.PropertyName, this.GetType ().Name));
switch (e.PropertyName)
{
default:
break;
}
}
public override void OnDestroyView ()
{
this.ViewModel.TearDown ();
base.OnDestroyView ();
}
}
I hope it makes sense to other people looking for solutions.
Creating ViewModels: So naturally, for every new ViewModel created, I had to register it in the ViewModelLocator.
Using ViewModels: In terms of usage, you can simply use the ViewModel in the UI by inheriting from the ": BaseViewModelUIViewController" for iOS or from ": BaseViewModelFragment" for Android
Unfortunately you don't miss anything, all your claims are proper and you have properly listed various directions that you can take (and that you don't like).
Xamarin.Android and Xamarin.iOS are not made with data binding in mind, but rather with using the native interfaces, only Xamarin.Forms is made for the data binding. The capabilities of native platforms to use the data binding is limited (if it existed it would be incompatible among the platforms and you would have to make separate view models, and there is not data binding for iOS as of now anyway).
So basically there is no data binding in Xamarin.iOS and Xamarin.Android. It is completely up to you to abstract the shared business model and connect it with the user interface.
Ok, so, I'm trying to link an ObservableCollection from my Android project to my Cross-Platform Project::
I've got this so far...this is in my Cross-platform app
ObservableCollection<String> NewRef = DependencyService.Get<ISlateBluetoothItems>().test().testThing;
NewRef.CollectionChanged += TestThing_CollectionChanged;
listView.ItemsSource = NewRef;
private void TestThing_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
listView.ItemsSource = DependencyService.Get<ISlateBluetoothItems>().test().testThing;
Console.WriteLine("working");
}
The line "working" is never printed even if I make changes to the ObservableCollection on the android portion of my app...
Here's the interface I'm using for the DependencyService:
using System.Collections.ObjectModel;
namespace ThoughtCastRewrite.BluetoothX
{
public interface ISlateBluetoothItems
{
BluetoothItems test();
}
}
Here's the class I use to expose the list:
namespace ThoughtCastRewrite.BluetoothX
{
public class BluetoothItems
{
public ObservableCollection<String> testThing;
public BluetoothItems()
{
testThing = new ObservableCollection<String>();
testThing.Add("wtf?");
}
public void AddThis()
{
testThing.Add("ok");
}
}
}
This is in the Android portion of my app, it implements the ISlateBluetoothItems interface
BluetoothItems bluetoothItems = new BluetoothItems();
then I call
bluetoothItems.AddThis();
but "ok" is not added to my list! I don't get the CollectionChanged event firing off! What's the deal guys? What's the deal?
You should assign your ObservableCollection as a source of your listview only once, not after each change. Changes to the collection will be automaticcly propagated to the listview.
I have a problem with xamarin.ios and MvvmCross, I need to display an MvxViewController and it comes in two ways depending on who calls it, I get it with:
CustomViewController:
public partial class CustomViewController : MvxViewController<CustomViewModel>, IMvxOverridePresentationAttribute
{
public CustomViewController() : base("CustomViewController", null)
{
}
public MvxBasePresentationAttribute PresentationAttribute()
{
if (ViewModel.KindNavigation) //Here's the issue
{
return new MvxSidebarPresentationAttribute(MvxPanelEnum.Center, MvxPanelHintType.ResetRoot, true, MvxSplitViewBehaviour.Detail);
}
else
{
return new MvxModalPresentationAttribute
{
ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen,
ModalTransitionStyle = UIModalTransitionStyle.CoverVertical
};
}
}
}
If I do ViewModel.anything, to get a parameter to define the type of presentation, the ViewModel, is null and I can't access. I have not even opened it, since the type of presentation for this view is not defined.
CustomViewModel:
public class CustomViewModel : MvxViewModel<string>, IDisposable
{
private readonly IMvxNavigationService _navigationService;
public CustomViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
}
private bool _KindNavigation;
public bool KindNavigation
{
get => _KindNavigation;
set => SetProperty(ref _KindNavigation, value);
}
public void Dispose()
{
throw new NotImplementedException();
}
public override Task Initialize(string parameter)
{
KindNavigation = Convert.ToBoolean(parameter);
System.Diagnostics.Debug.WriteLine("parameter: " + parameter);
return base.Initialize();
}
}
This is a restriction in MvvmCross, because the ViewModel is not loaded before the View is. This is also described in the documentation: https://www.mvvmcross.com/documentation/presenters/ios-view-presenter?scroll=446#override-a-presentation-attribute-at-runtime
To override a presentation attribute at runtime you can implement the IMvxOverridePresentationAttribute in your view controller and determine the presentation attribute in the PresentationAttribute method like this:
public MvxBasePresentationAttribute PresentationAttribute()
{
return new MvxModalPresentationAttribute
{
ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen,
ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve
};
}
If you return null from the PresentationAttribute the iOS View Presenter will fallback to the attribute used to decorate the view controller. If the view controller is not decorated with a presentation attribute it will use the default presentation attribute (a animated child presentation).
Note: Be aware that your ViewModel will be null during PresentationAttribute, so the logic you can perform there is limited here. Reason to this limitation is MvvmCross Presenters are stateless, you can’t connect an already instantiated ViewModel with a new View.
I've Inherted MvxListView to my CustomMvxListView where I dos something with the visualization when a child has been added or removed.
It works great but can be laggy when many items get bound.
Is there a way to detect when Mvx view controls are bound and loaded there first bound data?
Found a good solution myself;
To track Itemsource changes in Android in a ListView you can use a DataSetObserver.
like:
internal class MyObserver : DataSetObserver
{
private readonly object view;
public MvxListViewNonScrollableObserver(ViewToTrack view)
{
tView = view;
DoSomething():
}
public override void OnChanged()
{
base.OnChanged();
DoSomething():
}
}
Add it to a ListView by:
class MyMvxListView : MvxListView
{
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
itemsourceObserver = new MyObserver(this);
Adapter.RegisterDataSetObserver(itemsourceObserver);
}
protected override void OnDetachedFromWindow()
{
if (itemsourceObserver != null)
{
Adapter.UnregisterDataSetObserver(itemsourceObserver);
itemsourceObserver = null;
}
base.OnDetachedFromWindow();
}
public void DoSomething()
{
}
DoSomething() get raised after load and on every itemsource change.
I'm trying to understand how Caliburn.Micro works with Windows Phone (and MVVM in general) so I created a basic Windows Phone Application, installed Caliburn.Micro NuGet package (v1.2.0 - the latest for now) and followed the few instructions here and there. So, I ended up with:
WMAppManifest.xml
<DefaultTask Name ="_default" NavigationPage="Views/HomeView.xaml"/>
Framework/AppBootstrapper.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using Caliburn.Micro;
using MyCaliburn.PhoneUI.ViewModels;
namespace MyCaliburn.PhoneUI.Framework
{
public class AppBootstrapper : PhoneBootstrapper
{
PhoneContainer container;
protected override void Configure()
{
container = new PhoneContainer(RootFrame);
container.RegisterPhoneServices();
container.Singleton<HomeViewModel>();
}
protected override void OnUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
e.Handled = true;
}
else
{
MessageBox.Show("An unexpected error occured, sorry about the troubles.", "Oops...", MessageBoxButton.OK);
e.Handled = true;
}
base.OnUnhandledException(sender, e);
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
}
}
ViewModels/HomeViewModel.cs
using Caliburn.Micro;
namespace MyCaliburn.PhoneUI.ViewModels
{
public class HomeViewModel : Screen
{
public HomeViewModel()
{
//DisplayName = "Home";
}
}
}
View/HomeView.xaml.cs (the XAML page is the default Window Phone Portrait Page)
using Microsoft.Phone.Controls;
namespace MyCaliburn.PhoneUI.Views
{
public partial class HomeView : PhoneApplicationPage
{
public HomeView()
{
InitializeComponent();
}
}
}
App.xaml
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyCaliburn.PhoneUI.App"
xmlns:Framework="clr-namespace:MyCaliburn.PhoneUI.Framework">
<!--Application Resources-->
<Application.Resources>
<Framework:AppBootstrapper x:Key="bootstrapper" />
</Application.Resources>
</Application>
App.xaml.cs
using System.Windows;
namespace MyCaliburn.PhoneUI
{
public partial class App : Application
{
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Standard Silverlight initialization
InitializeComponent();
}
}
}
Now, when I hit F5, the application runs and exits without showing any page or exception and doesn't hit any breakpoints that I sit.
Can anyone tells me what's missing in my code which prevents the application from running?
Thanks in advance.
Many times when I end up with an app that does not start - it turns out that due to some refactoring the App class is not the startup object any more. Right-click on the project in solution explorer, go to properties/Application and make sure Startup object is set correctly.