2010-04-16 49 views
4

我需要TextBlock.Text從翻譯經理進行檢索,像的Silverlight:綁定到靜態值

<TextBlock Text="{Binding TranslateManager.Translate('word')}" /> 

我不想設置數據源的所有文本塊。我發現如何做到這一點的唯一方法是綁定到「靜態」類,並使用轉換器:

<TextBlock Text="{Binding Value, 
        Source={StaticResource Translation}, 
        Converter={StaticResource Translation}, 
        ConverterParameter=NewProject}" /> 

而且這些輔助類

public class TranslationManager : IValueConverter 
{ 
    public static string Translate(string word) 
    { 
    return translate(word); 
    } 

    // this is dummy for fake static binding 
    public string Value { get; set; } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
    var name = parameter as string; 
    return TranslationManager.Translate(name, name); 
    } 
} 

但是,有一個更好的 - 短 - 方法是什麼?

回答

3

最後讓我指出這樣的前綴:你應該使用靜態翻譯資源的話:Application Resources*.RESX Files

但是,如果您需要簡化您的xaml,唯一缺少的是在整個視圖中放置一個datacontext。這聽起來像你沒有使用MVVM,所以把這個邏輯在構造函數或後面的代碼爲您提供了通過有約束力的訪問更多的功能:

public MainPage() 
{ 
    // Required to initialize variables 
    InitializeComponent(); 


    // This is the key to simplify your xaml, 
    // you won't have set the source for individual controls 
    // unless you want to 
    DataContext = this;  
} 

然後,在你的XAML,你的文本框可以簡化到這一點:

<TextBlock Text="{Binding 
         ConverterParameter=Hi, 
         Converter={StaticResource Translator}}"/> 

我的翻譯:

public class Translator : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
      return "Hola!"; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
      return "Hi!"; 
    } 
} 
0

是的,Silverlight目前缺乏的一件大事是對其他標記擴展的支持 - x:靜態是其中一個更痛苦的擴展。

你現在正在做的是一種方式,毫無疑問。鄉親們嘗試了多種解決方法:

http://skysigal.xact-solutions.com/Blog/tabid/427/EntryId/799/Silverlight-DataBinding-to-a-static-resource.aspx

Using static objects in XAML that were created in code in Silverlight

但我還沒有找到一個「乾淨」的方式呢。至少沒有那樣乾淨「{X:靜態MyStaticClass.Member}」