Xamarin.Forms本地化
问题描述:
基于github上的解决方案,我想添加多语言到我的解决方案。 但是,我有我的代码隐藏,而不是XAML,所以我不知道如何在代码隐藏中执行双向绑定。Xamarin.Forms本地化
这里是我要转换为代码隐藏在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"
x:Class="myProj.Forms.Pages.LanguageSettingsPage"
Title="{Binding Resources[Settings]}">
<StackLayout>
<Label Text="{Binding Resources[PickLng]}" />
<Picker ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage, Mode=TwoWay}" />
</StackLayout>
</ContentPage>
,现在我隐藏的样子:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LanguageSettingsPage : ContentPage
{
public LanguageSettingsPage()
{
BindingContext = new SettingsViewModel();
//InitializeComponent();
StackLayout mainStack = new StackLayout();
mainStack.BackgroundColor = Constants.iBackgroundGray;
Label chooseLangLabel = new Label { TextColor = Constants.iGray };
chooseLangLabel.Text = LocalizationDemoResources.PickLng;
Picker langPicker = new Picker();
langPicker.SelectedItem = App.CurrentLanguage;
mainStack.Children.Add(chooseLangLabel);
mainStack.Children.Add(langPicker);
Content = mainStack;
}
}
而且我SettingsViewModel:
public class SettingsViewModel : ViewModelBase
{
public List<string> Languages { get; set; } = new List<string>()
{
"EN",
"NL",
"FR"
};
private string _SelectedLanguage;
public string SelectedLanguage
{
get { return _SelectedLanguage; }
set
{
_SelectedLanguage = value;
SetLanguage();
}
}
public SettingsViewModel()
{
_SelectedLanguage = App.CurrentLanguage;
}
private void SetLanguage()
{
App.CurrentLanguage = SelectedLanguage;
MessagingCenter.Send<object, CultureChangedMessage>(this,
string.Empty, new CultureChangedMessage(SelectedLanguage));
}
}
我资源文件的文件夹看起来像
如何绑定它,让我的后缀资源文件中的值填充选择器? 以及如何观察或有点,能够改变选择器中的项目点击语言?
谢谢。
答
SetBinding()的过载,允许您指定双向绑定
var l = new Label();
l.SetBinding(Label.TextProperty, ".", BindingMode.TwoWay);
我应该把,而不是“”?在哪里声明绑定到Label.Text属性的资源字段? – Stefan0309