WPF Binding to a method with parameter inside HierarchicalDataTemplate

Dested picture Dested · Nov 22, 2009 · Viewed 7.5k times · Source

Is there any way to bind a value to a textblock that is obtained from a method. For example, I pass my Person object into the HierarchicalDataTemplate, from there I can access its Weight property. Now lets say I want to get the weight in mars, I would call the InMars method that takes a parameter of int EarthWeight . Now earthweight is going to change from Person to Person, how can this parameter be set every time?

Answer

Cameron MacFarland picture Cameron MacFarland · Nov 23, 2009

The best way to do this is with a converter.

public class WeightOnMarsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // value will be the persons weight
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("This method should never be called");
    }
}

Then you just need to set up the binding.

<l:WeightOnMarsConverter x:key="weightOnMars" /> <-- Add this to the resources

{Binding Path=Weight, Converter={StaticResource weightOnMars}}