你做不需要任何標記擴展來實現這一點。你可以用一個簡單的ValueConverter來完成。
.resx文件添加到您的項目(在這個例子中,我們將其稱之爲Resource1.resx,有一個名爲「字符串1」值的字符串值「世界,你好!」)
創建一個轉換器,會將字符串轉換爲本地化的字符串。
namespace WpfApplication1.Converters
{
public class ResxLocalizationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string result = Resource1.ResourceManager.GetString(value.ToString());
if (result == null)
{
result = value.ToString();
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
添加一個轉換器實例的App.xaml
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml"
xmlns:converters="clr-namespace:WpfApplication1.Converters">
<Application.Resources>
<converters:ResxLocalizationConverter x:Key="ResxLocalizationConverter" />
</Application.Resources>
</Application>
把非本地化字符串值(或鑰匙)在您的XAML。
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBlock Text="{Binding Source='String1', Converter={StaticResource ResxLocalizationConverter}}"/>
</Grid>
</Window>
這將顯示 「世界,你好!」在TextBlock中。例如,您只需將Resource1.fr-FR.resx添加到Visual Studio項目(帶有名爲「String1」值的字符串值「Salut tout le monde!」)即可。例如,要爲法語本地化,您需要添加Resource1.fr-FR.resx。這將在法語本地化的PC上顯示法語版本,或者您可以使用ResourceManager.GetString(...)重載,以便您明確地選擇語言。
您還可以使用XAML資源實現本地化 –