简体   繁体   English

如何将基于键的字典值绑定到Code-Behind中的TextBlock?

[英]How do I bind Dictionary Value based on Key to a TextBlock in Code-Behind?

I am using the MVVM model with a dynamic field generator, where the field is pulled from the database, done this way because different types of forms require different fields (TextBox/TextBlock, ComboBox, etc.). 我将MVVM模型与动态字段生成器一起使用,该字段是通过数据库从字段中提取出来的,因为不同类型的表单需要不同的字段(TextBox / TextBlock,ComboBox等)。 The problem is I'm trying to retrieve a value from a dictionary, to display in a TextBlock for the form, but I'm not sure how to bind the retrieved Key so I can display the value. 问题是我试图从字典中检索一个值,以显示在表单的TextBlock中,但是我不确定如何绑定检索到的Key,以便显示该值。

Currently, I am doing the following: 目前,我正在执行以下操作:

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

With the following binding method: 使用以下绑定方法:

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

Where I pass something through like Score , which maps to a Score property in the ViewModel, but how would I bind to a Dictionary Key to retrieve its Value? 我在哪里通过诸如Score映射到ViewModel中的Score属性,但是如何绑定到Dictionary Key来检索其值?

I want to be able to bind to something like myDictionaryProperty[myDictionaryKey] , if that is possible. 我希望能够绑定到诸如myDictionaryProperty[myDictionaryKey]类的东西,如果可能的话。

Example: The below generates the PlayerScore for Player with ID of 1. Where PlayerScore is a Dictionary<int, int> and PlayerID is an int . 示例:下面为ID为1的Player生成PlayerScore 。其中PlayerScoreDictionary<int, int>PlayerIDint

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

Binding to indexed properties is possible and uses the same notation as C#, just like you wrote: 可以绑定到索引属性,并且使用与C#相同的符号,就像您写的一样:

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

The string you pass to "createFieldBinding" is the property path. 传递给“ createFieldBinding”的字符串是属性路径。 If you set the source as the dictionary, you just need to pass the indexer part, like "[ 1 ]", as if you had done like this in xaml: 如果将源设置为字典,则只需传递索引器部分,例如“ [ 1 ]”,就像在xaml中这样做一样:

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

See this 看到这个

Using this solution provided by @Clemens, I was able to build my own DictionaryItemConverter, based on the data types for my Dictionary, and create a multi-binding method that would bind the Key and the Dictionary together. 使用@Clemens提供的此解决方案 ,我能够根据我的Dictionary的数据类型构建自己的DictionaryItemConverter,并创建将KeyDictionary绑定在一起的多重绑定方法。

Converter: 转换器:

 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();
      }
 }

Multi-Bind Method: 多绑定方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM