Pergunta

Im attempting to bind to the output of a method. Now I've seen examples of this using ObjectDataProvider However the problem with this is ObjectDataProvider creates a new instance of the object to call the method. Where I need the method called on the current object instance. I'm currently trying to get a converter to work.

Setup:

Class Entity
{
   private Dictionary<String, Object> properties;

   public object getProperty(string property)
  {
      //error checking and what not performed here
     return this.properties[property];
  }
}

My attempt at the 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>

my code behind

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

My problem is that I cant seem to pass the current Entity into the converter. So When i try to use reflection to get the getProperty method I have nothing to operate on

thanks, steph

Foi útil?

Solução

Wrap the call to the method inside a get property and add this get property to whatever class that is your current DataContext.

Edit: Answering your updated question.

If you only pass one parameter to the valueconverter you don't need a multivalueconverter, just use a regular valueconverter (implementing IValueConverter). Also, why not cast the object in the valueconverter to a Distionary and use it directly instead of using reflection.

To pass current datacontext as a binding do this: <Binding . />. I'm guessing the datacontext of the textblock is entity.

Still, all this is not necessary if all you want to do is run some code before accessing a dictionary item. Just use an index property instead, you can databind to it directly:

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]}" />
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top