【问题标题】:Combobox ItemSource issue组合框 ItemSsource 问题
【发布时间】:2015-10-09 09:55:44
【问题描述】:

我有以下代码

<ComboBox x:Name="hotelComboBox"
          ItemsSource="{Binding HotelCollection}"
          SelectedItem="{Binding ActiveHotel,Mode=TwoWay}"
          Style="{StaticResource ComboBoxStyle}"
          HorizontalAlignment="Center"
          Visibility="{Binding IsFirstTimeUser, ConverterParameter=Inverse, Converter={StaticResource BooleanToVisibilityConverter}}">
    <TextBlock Text="Select Something"
               IsHitTestVisible="False">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="Visibility"
                        Value="Hidden" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=hotelComboBox,Path=SelectedItem}"
                                 Value="{x:Null}">
                        <Setter Property="Visibility"
                                Value="Visible" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style></TextBlock>
</ComboBox>

当我在组合框内添加 TextBlock 时,我收到一个错误,例如“在使用 ItemsSource 之前,项目集合必须为空。”

如果我删除项目源绑定,我不会收到此错误。但我需要使用此项目源。有什么选择吗?

谢谢

【问题讨论】:

  • 如果你不能发布整个代码(由于它的长度),至少发布一个有效的。在您的标记中,我没有看到组合框的结束标记,因此很难知道该 TextBox 是在里面还是在外面?
  • 是否在代码中设置ComboBox.Items 属性?
  • @Empereur Aiman 仍然是同样的错误,但我仍然需要在那里绑定。

标签: c# wpf xaml combobox


【解决方案1】:

您不能在使用ItemsSource 的同时在 XAML 中定义您的自定义项。

我猜,你要找的是ItemTemplateComboBox 的属性。

【讨论】:

    【解决方案2】:

    原因是Items是任何ItemsControl(如ComboBox)的内容属性。因此,当您将任何元素放入 ComboBox 时,它会自动添加到 Items 集合中。在您的情况下,您需要执行以下操作之一:

    • 在 ComboBox 附近声明 TextBlock
    • 使用ItemTemplate 属性
    • 停止使用 ItemsSource 并改用 Items

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2011-03-30
      • 2011-11-25
      相关资源
      最近更新 更多