【问题标题】:Binding XmlDataProvider Source attribute to a static function in another form?将 XmlDataProvider Source 属性绑定到另一种形式的静态函数?
【发布时间】:2011-02-16 19:59:24
【问题描述】:

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

这是 XmlDataProvider 行 -

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

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

【问题讨论】:

    标签: c# wpf xaml data-binding xmldataprovider


    【解决方案1】:

    请参阅 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 是行不通的。

    【讨论】:

    • 如果不是来自静态函数,是否可以从静态变量中获取值?怎么样?
    • 为此您可以使用{x:Static namespace:SomeClass.StaticProperty}
    • 我已经尝试过这样做,但是当我启动程序时它会给我一个错误报告。我添加了: xmlns:local="clr-namespace:Visual_Command_Line" 作为命名空间。我的代码:
    • 你得到的错误是什么? Settings 类是否在您指定的命名空间中?
    • “设置”类在我指定的命名空间中。我没有收到任何错误,当我启动程序时,我收到一条消息,说我的程序已停止使用 3 个按钮:"在线查看解决方案”、“关闭程序”、“调试程序”——通常的窗口不发送/发送错误报告
    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多