WPF中如何将ComboBox子元素的属性设为SelectedValuePath?
解决WPF ComboBox从嵌套TextBlock获取SelectedValue的问题
直接设置SelectedValuePath="Text"报错的核心原因是:SelectedValuePath的路径是基于SelectedItem(即ComboBoxItem实例)的,而ComboBoxItem本身并没有Text属性——你嵌套的TextBlock是作为ComboBoxItem的Content属性存在的,所以正确的路径应该是Content.Text。
修改后的完整ComboBox代码如下:
<ComboBox x:Name="CitySelectComboBox" SelectedValuePath="Content.Text"> <b:Interaction.Triggers> <b:EventTrigger EventName="Loaded"> <b:InvokeCommandAction Command="{Binding DownloadWeatherCommand}" CommandParameter="{Binding ElementName=CitySelectComboBox, Path=SelectedValue}" /> </b:EventTrigger> <b:EventTrigger EventName="SelectionChanged"> <b:InvokeCommandAction Command="{Binding DownloadWeatherCommand}" CommandParameter="{Binding ElementName=CitySelectComboBox, Path=SelectedValue}" /> </b:EventTrigger> </b:Interaction.Triggers> <ComboBoxItem IsSelected="True"> <TextBlock Text="Praha"/> </ComboBoxItem> <ComboBoxItem> <TextBlock Text="Brno"/> </ComboBoxItem> </ComboBox>
补充说明
- 当你把城市名直接写在ComboBoxItem的
Content属性时,Content是字符串类型,此时SelectedValuePath="Content"就能直接获取值;但嵌套TextBlock时,Content是TextBlock实例,必须通过Content.Text才能访问到文本内容。 - 如果后续Content结构可能变化,也可以给ComboBoxItem设置
Tag属性存储城市名,再将SelectedValuePath设为Tag,这种方式更稳定:
对应<ComboBoxItem IsSelected="True" Tag="Praha"> <TextBlock Text="Praha"/> </ComboBoxItem>SelectedValuePath="Tag"即可。
内容的提问来源于stack exchange,提问作者ampersander
相关产品推荐
相关产品推荐

