wpf xaml调用当前对象上的方法
我正在尝试绑定到方法的输出。现在我已经看到了使用wpf xaml调用当前对象上的方法,wpf,xaml,objectdataprovider,Wpf,Xaml,Objectdataprovider,我正在尝试绑定到方法的输出。现在我已经看到了使用ObjectDataProvider的例子,但是问题是ObjectDataProvider创建了一个新的对象实例来调用该方法。我需要在当前对象实例上调用的方法。我目前正在尝试让转换器工作 设置: Class Entity { private Dictionary<String, Object> properties; public object getProperty(string property) {
ObjectDataProvider
的例子,但是问题是ObjectDataProvider创建了一个新的对象实例来调用该方法。我需要在当前对象实例上调用的方法。我目前正在尝试让转换器工作
设置:
Class Entity
{
private Dictionary<String, Object> properties;
public object getProperty(string property)
{
//error checking and what not performed here
return this.properties[property];
}
}
我的问题是,我似乎无法将当前实体传递到转换器。因此,当我尝试使用反射来获取getProperty方法时,我没有什么可操作的
谢谢,steph将对方法的调用包装在get属性中,并将此get属性添加到当前DataContext的任何类中 编辑:回答更新的问题 如果只向valueconverter传递一个参数,则不需要多值转换器,只需使用常规valueconverter(实现IValueConverter)。另外,为什么不将valueconverter中的对象强制转换为Distionary并直接使用它,而不是使用反射呢 要将当前datacontext作为绑定传递,请执行以下操作:
。我猜textblock的datacontext是实体
不过,如果您只想在访问字典项之前运行一些代码,那么这一切都不是必需的。只需使用索引属性即可,您可以直接将数据绑定到它:
public class Entity
{
private Dictionary<String, Object> properties;
public object this[string property]
{
get
{
//error checking and what not performed here
return properties[property];
}
}
}
<TextBlock Text="{Binding Path=[Image]}" />
公共类实体
{
私有字典属性;
公共对象[字符串属性]
{
得到
{
//错误检查以及此处未执行的操作
归还财产[财产];
}
}
}
这方面的问题是属性字典可能包含许多内容。我不想为每个可能的属性编写get/set属性。您可以不使用方法将数据绑定到字典项。很好,直接附在字典上是可行的,但我不想让它公开发表。我喜欢在方法中进行错误检查。是否无法调用该方法来获取属性?同时,我还需要弄清楚如何使用DynamicPropertyIndex调用方法。也许是由一个下拉菜单/等等控制的,一个多值转换器,它带着字典和一个键。嘿,谢谢你,我离你越来越近了,但还没有得到它。。。我已经设置了一个多值转换器,但我不知道如何将当前对象作为“值”之一传入。我可以传递字符串“Images”,但当前正在操作的实体似乎无法传递给该方法。标准的{Binding Path=/}似乎不起作用。再次感谢
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string param = (string)parameter;
var methodInfo = values[0].GetType().GetMethod("getProperty", new Type[0]);
if (methodInfo == null)
return null;
return methodInfo.Invoke(values[0], new string[] { param });
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException("PropertyConverter can only be used for one way conversion.");
}
public class Entity
{
private Dictionary<String, Object> properties;
public object this[string property]
{
get
{
//error checking and what not performed here
return properties[property];
}
}
}
<TextBlock Text="{Binding Path=[Image]}" />