Silverlight的DataGrid即時變動多國語系

Silverlight的DataGrid即時變動多國語系

現在的網頁常常會需要多國語言,剛好我在做的專案也需要用到,而且還要即時改變!
前一篇寫過DataGrid的Header如何顯示資源檔的文字
但是卻只有在畫面載入的時候會變動,無法即時改變!
想要即時改變,就想到是否可以用Binding的方法,不過很可惜,
DataGridTextColumn的Header只吃文字,你給他其他物件,
也只會顯示Class.ToString()的值而已,
所以我們要擴充功能,我定義一個類別,繼承自DataGridTextColumn,
且註冊一個新的DependencyProperty,程式碼如下:

public class MyTextColumn : DataGridTextColumn{
    public static readonly DependencyProperty LocalizationHeaderProperty = 
        DependencyProperty.Register(
        "LocalizationHeader",
        typeof(string),
        typeof(MyTextColumn),
        new PropertyMetadata(null, new PropertyChangedCallback(LocalizationHeaderCallback)));

    public string LocalizationHeader {
        get { return (string)GetValue(LocalizationHeaderProperty); }
        set { SetValue(LocalizationHeaderProperty, value); }
    }

    private static void LocalizationHeaderCallback(object sender, DependencyPropertyChangedEventArgs e) {
        MyTextColumn mtc = sender as MyTextColumn;
        mtc.Header = e.NewValue;
    }
}

關於如何註冊DependencyProperty這裡就不多說。
最重要的就是在收到LocalizationHeader的時候要去改變Header的值。
接著為了讓xaml也可以用到資源檔,方法請看HOW TO:將 XAML 內容設定成可當地語系化
程式碼如下:

public class LanguageResource {
    private static Localization _Localization = new Localization();

    public Localization Localization { get { return _Localization; } }
}

如此我們就可以在XAML裡面直接設定LocalizationHeader

<local:MyTextColumn LocalizationHeader="{Binding Localization.Name,Source={StaticResource LResource}}"></local:MyTextColumn>

最後要讓他可以即時改變,那麼就需要INotifyPropertyChanged,
我們修改LanguageResource如下:

public class LanguageResource : INotifyPropertyChanged{
    private static Localization _Localization = new Localization();

    public Localization Localization { get { return _Localization; } }

    public void ChangeCulture(string culture) {
        Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Localization"));
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

除了繼承INotifyPropertyChanged介面之外,在多加一個改變文化的函式,
呼叫此函式,設定好文化之後,就會通知所有用到Localization的欄位了!

Silverlight的DataGrid即時變動多國語系.rar