2

是否有任何方法将值绑定到从方法获取的文本块。例如,我将Person对象传入HierarchicalDataTemplate,从那里我可以访问它的Weight属性。现在我们可以说我想在火星中获得体重,我会调用带有int EarthWeight参数的InMars方法。现在土方量将从人变为人,这个参数每次如何设置?WPF绑定到具有HierarchicalDataTemplate内部参数的方法

回答

3

要做到这一点的最佳方法是使用转换器。

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

然后你只需要设置绑定。

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

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