wpf XAML 绑定到带有参数的静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15520579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:11:49  来源:igfitidea点击:

XAML bind to static method with parameters

c#wpfxaml

提问by Gerrit

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:

现在我想在 xaml 中访问这个静态函数作为绑定。有没有这样的方法,例如:

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

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

或者是否有必要为每个可能的参数创建一个 ObjectDataProvider?

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

希望有人能够帮助我。提前致谢!

回答by Barzo

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:

然后将其用于 XAML:

<Window.Resources>
  <local:LanguageConverter x:Key="LangConverter" />
</Window.Resources>

<Label Content="{Binding Converter={StaticResource LangConverter}, 
                         ConverterParameter=ResourceKey}"/>

Regards.

问候。

回答by TYY

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 路线。虽然如果您只是绑定到文本而不是使用标签,我会使用文本块。

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