代码之家  ›  专栏  ›  技术社区  ›  T. Stone

WPF绑定到HierarchicalDataTemplate内具有参数的方法

  •  2
  • T. Stone  · 技术社区  · 15 年前

    是否有任何方法可以将值绑定到从方法获取的TextBlock。例如,我将Person对象传递到HierarchicalDataTemplate中,从中我可以访问它的Weight属性。现在假设我想得到火星的重量,我会调用in mars方法,它取一个int-earthweight参数。现在地球的重量会随着人的变化而变化,如何每次都设置这个参数呢?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Cameron MacFarland    15 年前

    最好的方法是使用转换器。

    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}}
    
    推荐文章