gpt4 book ai didi

c# - 如何将基于键的字典值绑定(bind)到代码隐藏中的 TextBlock?

转载 作者:行者123 更新时间:2023-12-02 09:40:05 28 4
gpt4 key购买 nike

我使用带有动态字段生成器的 MVVM 模型,其中字段是从数据库中提取的,这样做是因为不同类型的表单需要不同的字段(TextBox/TextBlock、ComboBox 等)。问题是我正在尝试从字典中检索一个值,以显示在表单的 TextBlock 中,但我不确定如何绑定(bind)检索到的键以便我可以显示该值。

目前,我正在执行以下操作:

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

采用以下绑定(bind)方法:

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

我经过的地方像 Score ,映射到 Score ViewModel 中的属性,但如何绑定(bind)到字典键以检索其值?

我希望能够绑定(bind)到类似 myDictionaryProperty[myDictionaryKey] 的内容,如果可能的话。

示例:下面生成 PlayerScore对于 ID 为 1 的玩家。哪里PlayerScoreDictionary<int, int>PlayerIDint .

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

最佳答案

可以绑定(bind)到索引属性,并使用与 C# 相同的表示法,就像您所写的那样:

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

传递给“createFieldBinding”的字符串是属性路径。如果将源设置为字典,则只需传递索引器部分,例如“[ 1 ]”,就像在xaml中这样做一样:

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

See this

关于c# - 如何将基于键的字典值绑定(bind)到代码隐藏中的 TextBlock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13802266/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com