WPF xml:lang/Language binding
how can i bind Listbox's or texblock's Language attribute (or xml:lang attribute).
i want to show month names in the specific language setting
ex:
<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>
result should be according to Lang 开发者_运维知识库property:
01.Apr.2011 - 01.Apr.2011 en-US
or 01.Nis.2011 - 02.Nis.2011 tr-TR
or ....
it gives XamlParseException : Language attribute cannot convert to System.Windows.Markup.XmlLanguage type (that is not exact Error Text. )
Any Idea?
In the Startup
event of the application, add this instruction:
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
It will override the default value of the Language
property to the current culture, for the whole application.
EDIT: ok, I had misunderstood your question...
If you want to bind the Language
property to a string containing the IetfLanguageTag
, you need a converter:
[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;
}
}
Declare the converter in the XAML resources:
<local:IetfTagToXmlLanguageConverter x:Key="languageConverter" />
And use the converter in the binding:
<TextBlock Language="{Binding Lang, Converter={StaticResource languageConverter}}">
you could create attached property and use it.
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}" />
精彩评论