0

我正在尝试将具有 Source 属性的 XmlDataProvider 绑定到另一种形式的静态函数。

这是 XmlDataProvider 行 -

<XmlDataProvider x:Key="Lang" Source="/lang/english.xml" XPath="Language/MainWindow"/>

我希望它的 Source 属性绑定到一个名为:“GetValue_UILanguage”的静态函数,形式为:“Settings”

4

1 回答 1

1

有关允许您绑定到方法的转换器,请参阅此问题的 答案。

您可能可以修改它以便也能够访问任何类的静态方法。

编辑:这是一个修改过的转换器,应该通过反射找到方法。

(注意:您最好使用标记扩展,因为您实际上并没有绑定任何值。)

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单独使用是行不通的。

于 2011-02-16T20:46:53.533 回答