How to switch UI Culture of data binding on the fly in Silverlight

前端 未结 2 1786
栀梦
栀梦 2021-01-03 11:19

I have a TextBlock control, which is data bound to DateTime property.

The text displayed something like this:

Thursday, October 21, 2010

I n

2条回答
  •  星月不相逢
    2021-01-03 11:30

    I've found a better approach, which requires to update only the root visual.

    public sealed class Localizer : INotifyPropertyChanged
    {
      public Localizer() 
      {
        Culture = Thread.CurrentThread.CurrentCulture; 
      }
    
      XmlLanguage _language;
      public XmlLanguage Language 
      { 
        get { return _language; } 
        private set { _language = value; RaiseOnPropertyChanged("Language"); } 
      }
    
      CultureInfo _culture;
      public CultureInfo Culture 
      { 
        get { return _culture; }
        set 
        { 
          Contract.Requires(value != null);  
    
          if (_culture == value) return; 
          _culture = value; 
    
          Thread.CurrentThread.CurrentCulture =
          Thread.CurrentThread.CurrentUICulture = value;
          Language = XmlLanguage.GetLanguage(value.Name);
    
          RaiseOnPropertyChanged("Culture");
        }
      }
    
      protected void RaiseOnPropertyChanged(string propName) 
      {
        var e = OnPropertyChanged;
        if (e != null) e(this, new PropertyChangedEventArgs(propName));
      }
    
      public event PropertyChangedEventHandler OnPropertyChanged;
    }

    Now adding this instance to application resources:

    
    

    Now bind it to your root visual (f.e. Frame, UserControl or Page) like this:

    
    

提交回复
热议问题