单击数据绑定的 ComboBoxItem 不会更新父 ComboBox

Clicking on databound ComboBoxItem doesn't update the parent ComboBox

我正在将字典绑定到 ComboBox ItemSource。一切都正确绑定,但是当我 运行 程序时,单击下拉菜单,然后单击该项目...没有任何反应。

其他有用的信息,当我点击每个项目的文本时,我可以在文本周围看到一个模糊的 box/border。如果我在框内单击,什么也不会发生。如果我在框外单击,一切都会按预期进行。想法?

我的xaml代码:

<ComboBox Name="PayloadDrop">
   <ComboBox.ItemTemplate>
      <ItemContainerTemplate>
         <ComboBoxItem Tag="{Binding Path=Key}" 
             Content="{Binding Path=Value}" />
         </ItemContainerTemplate>
      </ComboBox.ItemTemplate>
</ComboBox>

还有我后面的代码:

Dim PayloadDictionary As New Dictionary(Of Int16, String) From _
        {{0, "Some payload text"}, {1, "Path to a payload file"}}

PayloadDrop.ItemsSource = PayloadDictionary

下面是我的组合框的截图...

我对 ItemContainerTemplate 没有多少经验,但据我了解,DataTemplate 的情况也是如此。 (没有提及 Resources 或 MenuBase 或 StatusBar)

您将 KeyValuePair 项集合作为 ItemsSource。 KeyValuePair 不是 ComboBoxItem,因此 ComboBox 决定为其创建容器 - ComboBoxItem。此容器需要一种显示项目数据的方法,并且您已为此设置了 ItemTemplate,因此 another ComboBoxItem 是在容器内创建的。因此,您在 ComboBoxItem 中有 ComboBoxItem。外部 ComboBoxItem 与 ComboBox 相连,因此 ComboBox 会收到点击。内部的 ComboBoxItem 显示有淡淡的边框并且断开连接,所以对点击事件没有反应。
有两种可能的方法来更改您的 xaml:为 ItemTemplate 使用正确的 DataTemplate,或为 ItemContainerStyle 使用 Style。据我了解,您的任务是显示 Value 但同时保留有关 Key(某种 ID)的信息,因此您应该使用正确的 DataTemplate:

<ComboBox x:Name="PayloadDrop">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Value, Mode=OneTime}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
</ComboBox>

在这种情况下,ComboBox 将只显示值。您可以使用 SelectedValue 属性 访问它。 SelectedItem 属性 将包含基础 KeyValuePair。由于 KeyValuePair 没有实现 INotifyPropertyChanged,因此必须使用 Mode=OneTime 来避免内存泄漏。

您不需要在 DataTemplate 中定义 ComboboxItem,因为它将被隐式创建

<ComboBox Name="PayloadDrop" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Tag="{Binding Path=Key}" Padding="0" Margin="0"
         Text="{Binding Path=Value}" >                       
                </TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>