【问题标题】:How do I set the text a ComboBox displays when no item is selected (selected index is -1)? [duplicate]未选择任何项目时如何设置组合框显示的文本(选定索引为-1)? [复制]
【发布时间】:2015-09-02 17:19:46
【问题描述】:

我有一个ComboBox,它是数据绑定的,我无法插入哨兵项目。如果 ComboBox 中没有选定的值,我想显示一个默认字符串。

我已经尝试过为此使用样式:

<ComboBox.Style>
    <Style TargetType="ComboBox">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=SelectedIndex}" Value="-1">
                <Setter Property="Text" Value="(unconstrained)" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Style>

但这完全破坏了数据绑定(没有可选的值)。

【问题讨论】:

  • 在组合框中使用此代码PlaceholderText="MyPlaceholder"
  • 看看这个stackoverflow.com/questions/1426050/…也许是你需要的。
  • @soumyasambitKunda:System.Windows.Controls.ComboBox 没有 PlaceholderText 属性。也许那是 WinForms?
  • @Andrey: 是的,这个 hack 有效 :)

标签: c# wpf combobox


【解决方案1】:

你可以试试这个(不是很幸运)的解决方案: 您可以在列表的第一个位置添加另一个元素,其值为 "(unconstrained)",并在 XAML 中将 SelectedIndex 设置为 0。 Then, when selection changes, you delete this element from the underlying list for ComboBox and move selected index one place up (since the head of the list has been deleted).

这一点都不优雅,但似乎是唯一的解决方案,因为ComboBox 没有某种Header 属性,我不确定Text 对它做了什么(可能它只是继承)。

【讨论】:

  • 不幸的是,正如我在问题中指定的那样,我无法插入哨兵项目来执行此操作(我绑定到的集合已在数千个地方使用并修复它们以了解第一项是一个虚拟值是不可行的)
猜你喜欢
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
相关资源
最近更新 更多