XAML bind to static method with parameters

后端 未结 2 1956
一个人的身影
一个人的身影 2021-02-05 07:21

I got a static class like the following:

public static class Lang
{
   public static string GetString(string name)
   {
      //CODE
   }
}

Now

相关标签:
2条回答
  • 2021-02-05 07:28

    I get this need too. I "solved" using a converter (like suggested here).

    First, create a converter which return the translated string:

    public class LanguageConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        if (parameter == null)
          return string.Empty;
    
        if (parameter is string)
          return Resources.ResourceManager.GetString((string)parameter);
        else
          return string.Empty;
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotImplementedException();
      }
    }
    

    then use it into XAML:

    <Window.Resources>
      <local:LanguageConverter x:Key="LangConverter" />
    </Window.Resources>
    
    <Label Content="{Binding Converter={StaticResource LangConverter}, 
                             ConverterParameter=ResourceKey}"/>
    

    Regards.

    0 讨论(0)
  • 2021-02-05 07:38

    The right way would be to go the objectdataprovider route. Although if you are just binding to text rather than use a label, I would use a textblock.

    <ObjectDataProvider x:Key="yourStaticData"
                    ObjectType="{x:Type lang:Lang}"
                    MethodName="GetString" >
                    <ObjectDataProvider.MethodParameters> 
                         <s:String>Parameter1</s:String> 
                    </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    
    <TextBlock Text={Binding Source={StaticResource yourStaticData}}/>
    
    0 讨论(0)
提交回复
热议问题