2011-03-31 67 views
1

是否有可能在WPF中做這樣的事情? 假設我有一個這樣的類:WPF綁定新複雜類型的多個屬性

class Pair 
{ 
    public string A{get;set;} 
    public string B{get;set;} 
} 

和屬性PropertyA正確綁定,PropertyB正確綁定...

<SomeControl Tag="{Pair A="{Binding Path=PropertyA}", B="{Binding Path=PropertyB}" /> 

回答

3

您可以使用MultiBinding與轉換器:

<SomeControl> 
    <SomeControl.Tag> 
     <MultiBinding Converter="{StaticResource pairConverter}"> 
      <Binding Path="A" /> 
      <Binding Path="B" /> 
     </MultiBinding> 
    </SomeControl.Tag> 
</SomeControl> 

使用此轉換器:

public class PairConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (values.Length == 2) 
     { 
      return new Pair { A = (string)values[0], B = (string)values[1] }; 
     } 
     return Binding.DoNothing; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    { 
     Pair p = (Pair)value; 
     return new object[] { p.A, p.B }; 
    } 
}