【问题标题】:Clicking on databound ComboBoxItem doesn't update the parent ComboBox单击数据绑定的 ComboBoxItem 不会更新父 ComboBox
【发布时间】:2015-07-17 16:59:38
【问题描述】:

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

其他有用的信息,当我单击每个项目的文本时,我可以在文本周围看到一个模糊的框/边框。如果我在框内单击,则不会发生任何事情。如果我在框外单击,事情会按预期工作。想法?

我的 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

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

【问题讨论】:

  • 使用 DataTemplate 代替 ItemContainerTemplate。什么都没有发生您的意思是所选项目未显示在 ComboBox 中?
  • “什么都不会发生”我的意思是,从字面上看,什么都不会发生。我的 onclick 事件都不会触发(上面的代码中没有显示),组合框选定的项目不会更改为我单击的项目,下拉框不会再次隐藏。基本上,您在上面看到的屏幕截图会保留在那里......一旦我将代码从“ComboBoxItem”更改为“TextBlock”并将“Content”属性更改为“Text”,一切都开始完美运行。

标签: wpf vb.net .net-4.0


【解决方案1】:

我对 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。据我了解,您的任务是显示值,但也保留有关密钥(某种 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 来规避内存泄漏。

【讨论】:

  • Uggg...将它从组合项更改为文本块修复了它...浪费了很多时间...非常感谢。还要感谢@SamTheDev。显然我没有意识到组合框是自动创建的......
【解决方案2】:

您不需要在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>

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 2011-10-25
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多