绑定中的运行时文化更改和 IValueConverter [英] Run-time culture change and IValueConverter in a binding

查看:17
本文介绍了绑定中的运行时文化更改和 IValueConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的应用程序可以选择切换界面语言.这成功地改变了大部分 UI 本身,例如,

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}" />

除了静态 UI 元素外,还有一些显示一些模型的属性;对于他们中的大多数来说,不需要本地化,只有一个(现在).模型来自解决方案中的不同项目,并且是只读的.需要以其本地化形式显示的一个属性在模型中由其 ID 表示,我为它编写了一个转换器,返回一个资源字符串.

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;

等等.

在 XAML 文档中,它被绑定为

In the XAML document it gets bound as

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

...它可以工作,但只有一次,当 UI 元素第一次被绘制时(显然它也可以在 RankID 属性更改时工作,但这种情况很少发生).当文化改变时,它不会改变.我猜这是因为属性更改事件没有触发,所以 WPF 认为没有理由更新它.

…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?

推荐答案

我通过向底层模型添加新方法解决了这个问题.由于我使用的是 Livet 并且模型是 NotificationObject 的后代,因此我向相关模型添加了一个新的公共方法 Update()

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");

并添加

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

文化变更处理程序.

这篇关于绑定中的运行时文化更改和 IValueConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆