【问题标题】:SelectedItem not working in a wpf combobox after the itemtemplate has been modified修改项目模板后,SelectedItem 在 wpf 组合框中不起作用
【发布时间】:2020-04-10 05:40:52
【问题描述】:

我有一个组合框,我已将它绑定到字典。

字典定义为:

        Cities = new Dictionary<string, string>
        {
            {"USA", "NewYork"},
            {"UK", "London"},
            {"Canada", "Toronto"}
        };

组合框与字典的绑定如下:

                    <ComboBox x:Name="CitiesComboBox" Grid.Column="1" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity}" Margin="10" Background="Transparent">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="{Binding Key}" FontSize="15" VerticalAlignment="Center"/>
                                    <TextBlock Text="{Binding Value, Mode=OneWay, StringFormat='{}  {0}'}" VerticalAlignment="Center"/>
                                </StackPanel>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>

绑定工作正常,但我无法将组合框的选定项设置为“伦敦”。

由于 itemtemplate 不是单个字符串属性,因此组合框 selecteditem 属性未绑定到字符串值“London”

谢谢, 萨特

【问题讨论】:

    标签: wpf xaml combobox selecteditem itemtemplate


    【解决方案1】:

    您可以将SelectedValuePath 属性设置为“值”。然后,当您将SelectedValue 设置为“London”时,ComboBox 会将其选择映射到将“London”设置为其Value 属性的项目,这将解决您的问题 Here 是一篇详细介绍选择属性的不同用法的帖子。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 2016-06-09
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多