2012-12-10 5 views
2

다른 유형의 양식 (TextBox/TextBlock, ComboBox 등)을 필요로하기 때문에 동적 필드 생성기에서 MVVM 모델을 사용하고 있습니다. 여기서 필드는 데이터베이스에서 가져옵니다. 문제는 양식의 TextBlock에 표시하기 위해 사전에서 값을 검색하려고하지만 값을 표시 할 수 있도록 검색된 키를 바인딩하는 방법을 모르겠습니다. 다음 바인딩 방법으로키 기반 사전 값을 코드 숨김의 TextBlock에 바인딩하려면 어떻게해야합니까?

TextBlock textBlock = new TextBlock(); 
textBlock.SetBinding(TextBlock.TextProperty, createFieldBinding(myPropertyName); 

:

현재, 나는 다음과 같은 일을하고 내가 뷰 모델에 Score 속성에 매핑 Score 등을 통해 뭔가를 통과

private Binding createFieldBinding(string fieldName) { 
     Binding binding = new Binding(fieldName); 
     binding.Source = this.DataContext; 
     binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus; 
     return binding; 
} 

, 하지만 사전 키에 바인딩하여 값을 검색하는 방법은 무엇입니까?

가능한 경우 myDictionaryProperty[myDictionaryKey]과 같은 것으로 바인딩 할 수 있기를 바랍니다.

예 : PlayerScoreDictionary<int, int>PlayerIDint이고 어디 는 아래 1 의 ID와 플레이어의 PlayerScore를 생성한다.

<TextBlock Name="textBlockA" Text="{Binding PlayerScore[1]}" /> 

는 "createFieldBinding"에 전달하는 문자열 속성 경로 : 인덱스 속성에 바인딩

<TextBlock Name="textBlockA" Text="{Binding PlayerScore[1]} /> 
+1

당신은 (A [MultiBinding] 만들어야합니다 http://msdn.microsoft.com/en-us/library/ system.windows.data.multibinding.aspx), [이 질문에 대한 답변] (http://stackoverflow.com/q/13799705/1136211)에서 오늘 질문했습니다. – Clemens

+0

MVVM을 모르겠습니다. 나는 방금 Dictionary와 Path = Value에 Source를 사용한다. – Paparazzi

+0

@Clemens Awesome, 고마워! 내가 원했던 것을 위해 잠시 시간을 보냈지 만 그 해결책이 나를 위해 일한다. –

답변

3

제공 this solution를 사용 : 당신이 사전과 소스를 설정하면이 XAML에서 같이했던 것처럼, 당신은 단지 "[1]"와 같은, 인덱서 부분을 통과해야 @Clemens에 의해, My Dictionary의 데이터 유형을 기반으로 자체 DictionaryItemConverter를 구축하고 KeyDictionary을 함께 바인딩하는 다중 바인딩 메소드를 만들 수있었습니다.

변환기 :

public class DictionaryItemConverter : IMultiValueConverter { 
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 
      if(values != null && values.Length >= 2) { 
       var myDict = values[0] as IDictionary; 
       if(values[1] is string) { 
        var myKey = values[1] as string; 
        if(myDict != null && myKey != null) { 
          //the automatic conversion from Uri to string doesn't work 
          //return myDict[myKey]; 
          return myDict[myKey].ToString(); 
        } 
       } 
       else { 
        long? myKey = values[1] as long?; 
        if(myDict != null && myKey != null) { 
          //the automatic conversion from Uri to string doesn't work 
          //return myDict[myKey]; 
          return myDict[myKey].ToString(); 
        } 
       } 
      } 

      return Binding.DoNothing; 
     } 

     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { 
      throw new NotSupportedException(); 
     } 
} 

멀티 바인딩 방법 :

private MultiBinding createFieldMultiBinding(string fieldName) { 
     // Create the multi-binding 
     MultiBinding mbBinding = new MultiBinding(); 
     // Create the dictionary binding 
     Binding bDictionary = new Binding(fieldName + "List"); 
     bDictionary.Source = this.DataContext; 
     // Create the key binding 
     Binding bKey = new Binding(fieldName); 
     bKey.Source = this.DataContext; 
     // Set the multi-binding converter 
     mbBinding.Converter = new DictionaryItemConverter(); 
     // Add the bindings to the multi-binding 
     mbBinding.Bindings.Add(bDictionary); 
     mbBinding.Bindings.Add(bKey); 

     return mbBinding; 
} 
3

은 당신이 쓴 것처럼, 수 및 C#과 같은 표기법을 사용합니다.

<TextBlock Name="textBlockA" Text="{Binding [1]}" /> 

See this

+0

'1'이 속성이라면 어떨까요? –

+0

소스를 올바르게 설정하고 "1"이라는 속성에 바인딩하려면 "{Binding 1}"을 사용하십시오. "1"이 인덱스에 의해 반환 된 객체의 속성 인 경우 "{Binding [MyIndex] .1}"경로에 추가합니다 (바인딩 소스가 사전 또는 인덱서를 구현하는 객체라고 가정). C# 식별자는 숫자로 시작할 수 없습니다. http://msdn.microsoft.com/en-us/library/aa664670.aspx –

관련 문제