我有一个绑定(bind)到 viewModel 对象列表的 WPF 组合框。最初 SelectedItem 为空,因此 Combobox 显示为空白。
当所选项目为null时,我希望ComboBox显示“选择一个项目”,以指导用户从ComboBox中选择一些东西。有点像这样,一些文本框包含灰色文本,例如“输入用户名”
关于如何做到这一点有什么想法吗?
编辑:
我最终使用了 overlay a textbox, and change its visibility based on the value of SelecteItem 的建议
最佳答案
试试这个 - 根据您的代码更改 ItemsSource 和 SelectedValue。我刚刚展示了如何实现这一点..
<ComboBox Height="23" Name="comboBox1" Width="120" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}">
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<Trigger Property="SelectedIndex" Value="-1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ComboBox Text="Select an Item" IsReadOnly="True" IsEditable="True" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
或简单地->
<ComboBox Text="Select an Item" IsReadOnly="True" IsEditable="True" ItemsSource="{Binding OCString,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType=Window}}" SelectedValue="{Binding Selected,Mode=TwoWay,RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}"/>
关于c# - 当 selectedItem 为 null 时,在 Combobox 中显示 "Select an item",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18113293/