【发布时间】:2017-04-26 13:32:20
【问题描述】:
我有两个ComboBox。第一个的来源是dictionary,字符串作为键,对象作为值。选择一个项目后,第二个ComboBox 将填充来自所选项目的单独dictionary 的键。 When an item from the second ComboBox is selected, the TextBlock should show the value of the key that was chosen in the second ComboBox.但是,文本块总是显示为空。我已确保该值中确实包含实际数据,这让我相信这是一个绑定问题。
这是我的 ViewModel 的相关部分:
GPHDTModel gphdtModel = new GPHDTModel();
private Dictionary<string, object> models = new Dictionary<string, object>();
public Dictionary<string, object> Models
{
get
{
return models;
}
}
public MainWindowViewModel()
{
gphdtModel.MessageID = "3";
models.Add("GPHDT", gphdtModel);
}
接下来是 GPHDTModel:
private Dictionary<string, string> _fields = new Dictionary<string, string>();
public Dictionary<string, string> Fields
{
get
{
return _fields;
}
}
public GPHDTModel()
{
_fields.Add("MessageID", MessageID);
}
private string _messageID;
public string MessageID
{
get { return _messageID; }
set { _messageID = value; OnPropertyChanged("MessageID"); }
}
终于看到了:
<ItemsControl ItemsSource="{Binding DataModelCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<ComboBox x:Name="NMEAlist"
DisplayMemberPath="Key"
ItemsSource="{Binding Path=DataContext.Models,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}}}"
SelectedValuePath="Value" />
<ComboBox x:Name="ModelList"
DisplayMemberPath="Key"
ItemsSource="{Binding SelectedItem.Value.Fields,
ElementName=NMEAlist}"
SelectedValuePath="Value" />
<TextBlock Text="{Binding Value,
ElementName=ModelList}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
编辑:在TextBlock 的绑定中使用转换器进行调试,它显示了正确的键,在本例中为“MessageID”,但键的值为空,而它应该为“3”。
正如下面@mm8 所说,当像这样绑定文本块时:Text="{Binding SelectedItem.Key, ElementName=ModelList}"“MessageID”出现在文本块中。因此使用SelectedItem.Value 绑定是正确的,但值设置不正确。
【问题讨论】:
标签: c# wpf dictionary data-binding combobox