我当前的解决方案是对要本地化的属性(即TextBox's Text、Button's Content、ToolTips 等)使用 DataBinding 到全局可用的字符串集合,在换句话说,一个单身人士。就我而言,由于我使用的是 MVVM Light,我的 LocalizedStringCollection 被 ViewModelLocator 暴露。
此集合从 XLIFF 文件(请参阅 https://en.wikipedia.org/wiki/Xliff)加载到我的集合成员 Dictionary<string, string> 中。
这里是公开字符串的集合的关键部分。
/// <summary>
/// A Singleton bindeable collection of localized strings.
/// </summary>
public class LocalizedStringCollection : ObservableObject, INotifyCollectionChanged
{
private Dictionary<string, string> _items;
/// <summary>
/// The content of the collection.
/// </summary>
public Dictionary<string, string> Items
{
get { return _items; }
private set
{
_items = value;
RaisePropertyChanged();
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
/// <summary>
/// Convenience accessor, most likely entry point.
/// </summary>
/// <param name="key">A localized string name</param>
/// <returns>The localized version if found, an error string else (ErrorValue in DEBUG mode, the key in RELEASE)</returns>
public string this[string key]
{
get
{
Contract.Requires(key != null);
Contract.Ensures(Contract.Result<string>() != null);
string value;
if (Items.TryGetValue(key, out value))
return value ?? String.Empty;
#if DEBUG
return ErrorValue;
#else
return key;
#endif
}
}
}
使用内置 XML 支持,XLIFF 解析很简单。
这里是 XAML 使用示例(根据所使用的语法可能或多或少冗长):
<TextBlock Text="{Binding LocalizedStrings[login_label], Source={StaticResource Locator}}" />
<Button ToolTipService.ToolTip="{Binding LocalizedStrings[delete_content_button_tip], Source={StaticResource Locator}}" />
希望这会有所帮助:)
如果人们有兴趣,我可能会写一篇关于此的文章(带有完整来源)。