简体   繁体   中英

Run-time culture change and IValueConverter in a binding

The application I'm working on has an option to switch the interface language. This successfully changes most of the UI itself which uses, for example,

<Run Text="{Binding Resources.CreditsTitle, Source={x:Static models:ResourceService.Current}, Mode=OneWay}" />

Aside from static UI elements there are some displaying a few models' properties; for most of them no localisation is necessary, save for just one (for now). The models come from a different project within the solution, and are read-only. The one property that needs to be displayed in its localised form is represented by its ID in the model, and I wrote a converter for it that returns a Resource string.

public class RankIDToRankNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int)
        {
            var ID = (int)value;
            switch (ID)
            {
                case 1:
                    return Resources.Rank_Expert;
                case 2:
                    return Resources.Rank_Intermediate;

And so on.

In the XAML document it gets bound as

<Run Text="{Binding Model.RankID, Converter={StaticResource RankIDToRankNameConverterKey}, Mode=OneWay}"
         Style="{DynamicResource PickupTextElementStyleKey}"
         FontSize="14" />

…and it works, but just once, when the UI element gets drawn for the first time (obviously it also works when the RankID property changes but that happens extremely rarely). It doesn't change when culture is changed. I'm guessing it's because the property changed event does not fire, so WPF sees no reason to update it.

What's the “proper” way to get it to update when culture is changed?

I have solved this issue by adding a new method to the underlying model. Since I'm using Livet and models are NotificationObject descendants, I added a new public method Update() to the model in question with

this.RaisePropertyChanged("changed_property_name_here");

and adding

try
{
    InstanceOfModelStorage.UnderlyingModel.Update();
}
catch (NullReferenceException e) { }

to the culture change handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM