当 selectedItem 为 null 时,在 Combobox 中显示“选择一项”

2023-12-19

我有一个绑定到 viewModel 对象列表的 WPF 组合框。最初,SelectedItem 为空,因此组合框显示为空白。

当所选项目为空时,我希望组合框显示“选择项目”以引导用户从组合框中选择某些内容。有点像这样,一些文本框包含灰色文本,例如“输入用户名”

关于如何做到这一点有什么想法吗?

Edit:

我最终使用了该建议覆盖文本框,并根据 SelecteItem 的值更改其可见性 https://stackoverflow.com/questions/1426050/how-to-display-default-text-select-team-in-combo-box-on-pageload-in-wpf


尝试这个 - 根据您的代码更改 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}"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 selectedItem 为 null 时,在 Combobox 中显示“选择一项” 的相关文章

随机推荐