Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML bind to static method with parameters

Tags:

c#

wpf

xaml

I got a static class like the following:

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

Now i want to access this static function within xaml as a binding. Is there such a way for example:

<Label Content="{Binding Path="{x:static lang:Lang.GetString, Parameters={parameter1}}"/>

Or is it necessary to create a ObjectDataProvider for each possible parameter?

Hope someone is able to help me. Thanks in advance!

like image 695
Gerrit Avatar asked Mar 20 '13 10:03

Gerrit


2 Answers

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.

like image 171
Barzo Avatar answered Oct 17 '22 03:10

Barzo


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}}/>
like image 45
TYY Avatar answered Oct 17 '22 01:10

TYY