有趣的是,它们都联系在一起。
对于 2) 和 3),您需要创建一个控制器来保存ResourceLoader
目的。您可以使用(如果使用 Windows 8.1),ResourceLoader.GetForIndependentUse()
.
在你的中创建一个方法ResourceController
called GetTranslation(string resource)
。它看起来像这样:
private static ResourceLoader resourceLoader = ResourceLoader.GetForIndependentUse();
public static string GetTranslation(string resource)
{
return resourceLoader.GetString(resource);
}
然后,每当您需要静态编码翻译时,只需调用ResourceController.GetString(*key of the string you want*)
.
这对于简单的代码调用非常有用,但不能直接用于 Xaml,例如您的场景 1)。不过不用担心,因为您拥有转换器的魔力!
public class ResourceTranslationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var valString = value as string;
// If what is being converted is a string, return the resource translation
// Else return something else, such as the object itself
return valString == null ? value : ResourceController.GetString(valString);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
然后,您所要做的就是定义一次转换器(可能可以从您的所有 xaml 访问,可能是一个字典合并到您的App.xaml
)并且您可以随时在绑定中引用它!
对于这个例子,类似:
<!-- This is defined somewhere accessible, or just in the Page Resources -->
<!-- 'converters' is whichever namespace definition your converter is in -->
<converters:ResourceTranslationConverter x:Key="ResourceTranslationConverter"/>
<ComboBox x:Name="comboBoxTopAppBar" Width="120" Margin="10,0,0,0" MinWidth="200"
SelectedItem="{Binding SelectedStatus, Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource ResourceTranslationConverter}}"
</DataTemplate>
<ComboBox.ItemTemplate>
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
<x:String>Item 3</x:String>
</ComboBox>
这样你的所有文本都会通过你的ResourceLoader
在运行时自动执行。您定义的任何新项目也将自动翻译(只要它们在您的资源中有条目并且已翻译)。
希望这对您有所帮助,祝您编码愉快!