我正在学习 C#、WPF 和 XAML,此时我的目标是产品的国际化。
我可以在 Resources.resx 中定义要翻译的字符串,并且我希望能够在我的 XAML 文件中使用这些字符串时对其进行操作。举个例子,假设有这样一个标签
<Label Grid.Column="0" Grid.Row="0" Content="{x:Static p:Resources.username}" />
在 Resources.resx 中,我定义了名称 username
和值 username
并且标签获得了正确的值。
假设现在我想显示另一个标签,但这次我想显示文本 Username
,大写 u。直接的解决方案是定义名称 Username
值 Username
,但我得到了重复的资源。在其他模板系统中,例如在 django 中,我可以使用初始资源,并且可以应用过滤器来修改字符串,但我无法在 C# 中实现这一点。
有没有办法在 C# 和 XAML 中对静态资源进行多种操作,例如应用一个将字符串首字母大写的转换器?
最佳答案
Binding
有一个 Converter
属性。所以你可以绑定(bind)到静态资源并使用转换器来修改值:
<Window.Resources>
<local:StrToLowerValueConverter x:Key="strToLowerCnv"/>
</Window.Resources>
<Label Grid.Column="0" Grid.Row="0" Content="{Binding Source={x:Static p:Resources.username}, Mode=OneWay, Converter={StaticResource strToLowerCnv}}" />
和转换器本身:
public class StrToLowerValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value as string)?.ToLower() ?? value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
关于c# - 在 XAML 中操作静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505446/