c# - 当 selectedItem 为 null 时,在 Combobox 中显示 "Select an item"

标签 c# wpf mvvm combobox

我有一个绑定(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/

相关文章:

c# - 不使用第 3 方工具从头开始开发 Word 到 PDF 转换器

c# - 您如何对相互递归方法进行单元测试?

c# - INavigation 无法在 Xamarin.Forms 中使用 Prism

.net - MVVM-light 中的清理与处置( bool )

c# - 跨聚合根搜索 child

c# - 错误 : An unhandled exception of type 'System.BadImageFormatException' occurred in System. Windows.Forms.dll

c# - 重新评估 UniformGrid 行和列 WPF

wpf - 特殊字符wpf

wpf - DataGrid 通过单击 UpdateSourceTrigger = SourceUpdated 捕获单元格值更改事件

c# - 使用Newtonsoft和biding View(MVVM)反序列化JSON