23

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!

2
  • Could you not create a converter, or format the string e.g. Content="{Binding Path=MyValue, StringFormat=You searched for {0}}"/> ? Commented Mar 20, 2013 at 10:33
  • the string.Format was just a example output. Will clearify the question. Commented Mar 20, 2013 at 10:38

2 Answers 2

24

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}"/> 
Sign up to request clarification or add additional context in comments.

Comments

7

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}}/> 

3 Comments

Thanks for the answer, but this approach would mean i have to create a own ObjectDataProvider for every different parameter. Or is it possible to change the ObjectDataProvider parameter through the binding statement? For example: <TextBlock Text={Binding Source={StaticResource yourStaticData[parameter1]}}/>
Looking at the msdn linking the only way my suggestion would work is if the MethodParameters was bound to something that specified the value. So I guess my answer might not be what you are looking for. weblogs.asp.net/psheriff/archive/2010/02/23/…
Thanks anyway for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.