请参阅 this question's answer 了解允许您绑定到方法的转换器。
您可以修改它,使其也能够访问任何类的静态方法。
编辑:这是一个修改过的转换器,它应该通过反射找到方法。
(注意:你最好使用markup extension,因为你实际上并没有绑定任何值。)
public sealed class StaticMethodToValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
var methodPath = (parameter as string).Split('.');
if (methodPath.Length < 2) return DependencyProperty.UnsetValue;
string methodName = methodPath.Last();
var fullClassPath = new List<string>(methodPath);
fullClassPath.RemoveAt(methodPath.Length - 1);
Type targetClass = Assembly.GetExecutingAssembly().GetType(String.Join(".", fullClassPath));
var methodInfo = targetClass.GetMethod(methodName, new Type[0]);
if (methodInfo == null)
return value;
return methodInfo.Invoke(null, null);
}
catch (Exception)
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("MethodToValueConverter can only be used for one way conversion.");
}
}
用法:
<Window.Resources>
...
<local:StaticMethodToValueConverter x:Key="MethodToValueConverter"/>
...
</Window.Resources>
...
<ListView ItemsSource="{Binding Converter={StaticResource MethodToValueConverter}, ConverterParameter=Test.App.GetEmps}">
...
App类中的方法:
namespace Test
{
public partial class App : Application
{
public static Employee[] GetEmps() {...}
}
}
我对此进行了测试,它可以正常工作,但使用完整的类路径很重要,单独使用 App.GetEmps 是行不通的。