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}}