【问题标题】:wpf xaml calling a method on the current objectwpf xaml 在当前对象上调用方法
【发布时间】:2010-09-15 20:08:01
【问题描述】:

我正在尝试绑定到方法的输出。现在我已经看到了使用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];
  }
}

我对 XAML 的尝试

     <local:PropertyConverter x:Key="myPropertyConverter"/>
      <TextBlock Name="textBox2">
          <TextBlock.Text>
            <MultiBinding Converter="{StaticResource myPropertyConverter}"
                          ConverterParameter="Image" >
              <Binding Path="RelativeSource.Self" /> <!--this doesnt work-->
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>

我的代码在后面

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.");
}

我的问题是我似乎无法将当前实体传递给转换器。所以当我尝试使用反射来获取 getProperty 方法时,我没有什么可操作的

谢谢,斯蒂芬

【问题讨论】:

    标签: wpf xaml objectdataprovider


    【解决方案1】:

    将对方法的调用封装在一个 get 属性中,并将这个 get 属性添加到当前 DataContext 的任何类中。

    编辑:回答您更新的问题。

    如果您只将一个参数传递给 valueconverter,则不需要 multivalueconverter,只需使用常规 valueconverter(实现 IValueConverter)。另外,为什么不将 valueconverter 中的对象转换为 Distionary 并直接使用它而不是使用反射。

    要将当前数据上下文作为绑定传递,请执行以下操作:&lt;Binding . /&gt;。我猜文本块的数据上下文是实体。

    不过,如果您只想在访问字典项之前运行一些代码,那么这一切都不是必需的。只需使用索引属性,您可以直接对其进行数据绑定:

    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 属性
    • 您可以在不使用方法的情况下将数据绑定到字典项。
    • 直接附在字典上很有效,但我很犹豫是否将其公开。我喜欢在方法中进行错误检查。有没有办法调用方法来获取属性?此外,我还需要弄清楚如何使用动态属性索引调用方法。也许由下拉/等控制
    • 使用一个多值转换器,它接受字典和一个键。
    • 嘿,非常感谢你,我越来越近了,但还没有得到它...我已经设置了一个多值转换器,但无法弄清楚如何将当前对象作为其中之一传递价值观”。我可以传递字符串“Images”,但当前正在操作的实体似乎无法传递给该方法。标准的 {Binding Path =/} 似乎不起作用。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多