好吧,我不想在我的MVVM视图模型中有一堆icommands,所以我决定为wpf创建一个markupextension,您向它提供一个字符串(方法的名称),它将返回一个执行该方法的icommand。
下面是一个片段:
public class MethodCall : MarkupExtension
{
public MethodCall(string methodName)
{
MethodName = methodName;
CanExecute = "Can" + methodName;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
Binding bin = new Binding { Converter = new MethodConverter(MethodName, CanExecute) };
return bin.ProvideValue(serviceProvider);
}
}
public class MethodConverter : IValueConverter
{
string MethodName;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//Convert to ICommand
ICommand cmd = ConvertToICommand();
if (cmd == null)
Debug.WriteLine(string.Format("Could not bind to method 'MyMethod' on object", MethodName));
return cmd;
}
}
它工作得很好,除非绑定失败(例如您输入错误)。
在XAML中执行此操作时:
{Binding MyPropertyName}
每当绑定失败时,都会在输出窗口中看到。它告诉你属性名,类型名等等。
methodConverter类可以告诉您失败的方法的名称,但不能告诉您源对象类型。因为值将为空。
我不知道如何存储源对象类型,因此对于以下类
public class MyClass
{
public void MyMethod()
{
}
}
以及以下XAML:
<Button Command={d:MethodCall MyMethod}>My Method</Button>
它目前说:
"Could not bind to method 'MyMethod' on object
但我想说:
"Could not bind to method 'MyMethod' on object MyClass
有什么想法吗?