如何在Silverlight中即时切换UI文档的数据绑定

问题描述:

我有一个TextBlock控件,它是绑定到DateTime属性的数据。

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

如下所示:

2010年10月21日,星期四

Thursday, October 21, 2010

我需要即时切换UI文化,使用这样的东西:

I need to switch UI Culture on the fly, using something like this:

Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture 
                                    = new CultureInfo("de-de");

我已经尝试强制绑定重新计算:

I've tried this to force binding to recalc:

var bindingExpression = textBlock.GetBindingExpression(TextBlock.TextProperty);
bindingExpression.UpdateSource();

但是我仍然看到星期四而不是Donnerstag ...

But I still see Thursday instead of Donnerstag...

如何继续?任何想法?

我发现了一个更好的方法,它只需要更新根视觉。

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:

<nt:Localizer x:Key="Localizer"/>

现在将其绑定到您的根视觉(fe Frame,UserControl或Page) >

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

<UserControl ... Language="{Binding Language, Source={StaticResource Localizer}}">