Xamarin.forms在运行时更改语言

时间:2020-08-20 11:36:54

标签: xamarin.forms localization

我有一个登录页面,我的代码是这样:

    <ContentPage.Content>
        <Grid>
            <StackLayout Orientation="Vertical" Padding="20">
                <Entry Placeholder="{x:Static resources:AppResources.EMB_PLACEHOLDER}" Keyboard="Numeric"  Text="{Binding EMB}"></Entry>
                <Button Text="{x:Static resources:AppResources.LOGIN_BTN}" TextColor="White" Padding="0,-20" BackgroundColor="#07987f" Command="{Binding LoadLoginCommand}"></Button>
                <Label
                 Margin="0,10,0,0" >
                    <Label.FormattedText>
                        <FormattedString>
                            <Span Text="{x:Static resources:AppResources.MESSAGE} "></Span>
                        </FormattedString>
                    </Label.FormattedText>
                </Label>
                <Grid Margin="0,10,0,0" >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Label Padding="20,0,0,0" Text="{x:Static resources:AppResources.LBLLANGUAGE}" VerticalOptions="Center" FontSize="Body" TextColor="Gray" Grid.Column="0"/>
                    <Picker x:Name="languagePicker" Grid.Column="1" ItemsSource="{Binding Languages}" Title="{x:Static resources:AppResources.LBLLANGUAGE}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedLanguage, Mode=TwoWay}"></Picker>
                </Grid>
            </StackLayout>
            <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                <ActivityIndicator IsVisible="{Binding IsBusy}" IsRunning="{Binding IsBusy}" HorizontalOptions="Center" VerticalOptions="Center"></ActivityIndicator>
                <Label Text="{x:Static resources:AppResources.TSMSG1}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" HorizontalOptions="Center" VerticalOptions="Center" IsVisible="{Binding IsBusy}"/>
            </StackLayout>
        </Grid>
    </ContentPage.Content>

具有带有语言列表的选择器。每种语言都有resx文件。我的情况是,当我单击选择器并选择某种语言时,我想以所选语言实时更改登录页面上所有文本的语言。知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

注释中提供的第一个链接是一个了不起的解决方案,但是为了简化起见,一种非常简单的方法是将控件的文本绑定到ViewModel中的属性:

<Label Text="{Binding TSMSG1}"...

而不是使用

<Label Text="{x:Static resources:AppResources.TSMSG1}"...

然后,在ViewModel中,您将拥有属性TSMSG1(及其他),可以在语言更改时手动更新该属性。当然,这些属性需要遵循INPC模式才能使更改反映在视图上。

我不建议在任何地方都这样做,因为绑定对于您的应用程序性能而言代价很高,但是对于更改语言的屏幕来说应该没问题。