2009-11-24 4 views
3

나는 X[Y] 나에게 형 Z의 또 다른 객체를 제공합니다 가정 X라는 클래스에 Indexer 속성을 가지고있다? 내가 할 경우 작동 {Binding [0]}. 그러나 {Binding X[Y]}은 인덱서 매개 변수를 Y 인 문자열로 사용합니다.XAML 인덱서 데이터 바인딩

는 업데이트 : Converter는 옵션입니다,하지만 난 인덱서와 뷰 모델 클래스의 많음을 가지고 비슷한 모음이없는, 그래서 모든 사람들을위한 별도의 컨버터를 만들 여유가 없다. 그래서 WPF에서 지원되는지 알고 싶다면, 어떻게 선언 할 것입니까? Content=X[Y] 여기서 XYDataContext 속성입니까?

답변

2

이 작업을 수행하는 유일한 방법은 MultiBindingIMultiValueConverter입니다.

<TextBlock DataContext="{Binding Source={x:Static vm:MainViewModel.Employees}"> 
    <TextBlock.Text> 
     <MultiBinding Converter="{StaticResource conv:SelectEmployee}"> 
      <Binding /> 
      <Binding Path="SelectedEmployee" /> 
     </MultiBinding> 
    </TextBlock.Text> 
</TextBlock> 

그리고 당신의 계산기 :

public class SelectEmployeeConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     Debug.Assert(values.Length >= 2); 

     // change this type assumption 
     var array = values[0] as Array; 
     var list = values[0] as IList; 
     var enumerable = values[0] as IEnumerable; 
     var index = Convert.ToInt32(values[1]); 

     // and check bounds 
     if (array != null && index >= 0 && index < array.GetLength(0)) 
      return array.GetValue(index); 
     else if (list != null && index >= 0 && index < list.Count) 
      return list[index]; 
     else if (enumerable != null && index >= 0) 
     { 
      int ii = 0; 
      foreach (var item in enumerable) 
      { 
       if (ii++ == index) return item; 
      } 
     } 

     return Binding.DoNothing; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, 
     object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

네 덕분에 단 하나의 클래스가있는 경우이 확실한 솔루션입니다. 하지만 이것과 비슷한 ViewModel 클래스가 많이 있습니다. 그래서 별도의 변환기가 필요하지 않습니다. 대신 Indexer 논리를 다른 것으로 변경합니다. –

+0

나는 많은 컬렉션 유형에서 작동하도록이 글을 올리고 업데이트했다. – user7116