我正在使用带动态字段生成器的MVVM模型,其中字段从数据库中拉出,这样做是因为不同类型的表单需要不同的字段(TextBox/TextBlock,ComboBox等)。问题是我试图从字典中检索一个值,以在TextBlock中显示表单,但我不知道如何绑定检索到的键,以便显示值。如何在代码背后将基于密钥的字典值绑定到TextBlock?
目前,我做了以下内容:
TextBlock textBlock = new TextBlock();
textBlock.SetBinding(TextBlock.TextProperty, createFieldBinding(myPropertyName);
下面的结合方法:
private Binding createFieldBinding(string fieldName) {
Binding binding = new Binding(fieldName);
binding.Source = this.DataContext;
binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
return binding;
}
当我穿过像Score
的东西,它映射到一个Score
财产视图模型,但我如何绑定到一个字典键来检索它的值?
我希望能够绑定到类似myDictionaryProperty[myDictionaryKey]
的东西,如果可能的话。
实施例: 的下面的1 ID生成PlayerScore
为播放器在哪里PlayerScore
是Dictionary<int, int>
和PlayerID
为int
。
<TextBlock Name="textBlockA" Text="{Binding PlayerScore[1]} />
你将不得不建立一个[MultiBinding(http://msdn.microsoft.com/en-us/library/ system.windows.data.multibinding.aspx),如[本问题](http://stackoverflow.com/q/13799705/1136211)的答案中所述。 – Clemens
我不知道MVVM。我只是使用源文本和路径=值 – Paparazzi
@Clemens真棒,谢谢你!花了我一段时间来修补我想要的东西,但该解决方案适用于我。 –