如何绑定Listbox或texblock的Language属性(或xml:lang属性)。
我想在特定语言设置中显示月份名称
例如:
<TextBlock x:Name="Date" xml:lang="{Binding Lang}">
<TextBlock.Text>
<MultiBinding StringFormat=" {0:dd.MMM.yyyy}-{1:dd.MMM.yyyy}">
<Binding Path="Date1"/>
<Binding Path="Date2"/>
</MultiBinding>
</TextBlock.Text>
结果应该是郎属性:
01.Apr.2011 - 01.Apr.2011 en-US
或01.Nis.2011 - 02.Nis.2011 tr-TR
或......
它给出了XamlParseException:语言属性无法转换为System.Windows.Markup.XmlLanguage类型(这不是精确的错误文本。)
任何想法?
答案 0 :(得分:5)
在应用程序的Startup
事件中,添加以下指令:
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
对于整个应用程序,它将覆盖当前区域性的Language
属性的默认值。
如果要将Language
属性绑定到包含IetfLanguageTag
的字符串,则需要转换器:
[ValueConversion(typeof(string), typeof(XmlLanguage))]
public class IetfTagToXmlLanguageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string tag = value as string;
if (tag == null)
return Binding.DoNothing;
return XmlLanguage.GetLanguage(tag);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
XmlLanguage lang = value as XmlLanguage;
if (lang == null)
return Binding.DoNothing;
return lang.IetfLanguageTag;
}
}
在XAML资源中声明转换器:
<local:IetfTagToXmlLanguageConverter x:Key="languageConverter" />
并在绑定中使用转换器:
<TextBlock Language="{Binding Lang, Converter={StaticResource languageConverter}}">
答案 1 :(得分:2)
您可以创建附加属性并使用它。
sealed class CultureBehavior
{
public static DependencyProperty CultureProperty =
DependencyProperty.RegisterAttached("Culture",
typeof (string),
typeof (CultureBehavior),
new UIPropertyMetadata(OnCultureChanged));
public static void SetCulture(FrameworkElement target, string value)
{
target.SetValue(CultureProperty, value);
}
public static string GetCulture(FrameworkElement target)
{
return (string) target.GetValue(CultureProperty);
}
private static void OnCultureChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
var element = target as FrameworkElement;
if (element == null) return;
element.Language = XmlLanguage.GetLanguage(args.NewValue.ToString());
}
}
XAML
xmlns:local="clr-namespace:App.Utils"
....
<TextBlock Text="{Binding Repairs, StringFormat=c}" local:CultureBehavior.Culture="{Binding CultureString}" />