XAML bind to static method with parameters

眉间皱痕 提交于 2020-05-24 21:18:10

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/15520579/xaml-bind-to-static-method-with-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!