Display “Select an item” in Combobox when selectedItem is null

只愿长相守 提交于 2020-01-04 12:47:16

问题


I have a WPF Combobox that is bound to a list of viewModel objects. Initially the SelectedItem is null, and thus the Combobox display is blank.

When the selected item is null, I would prefer the Combobox to display "Select an item" to guide the user to select something from the combobox. sort of like the way, some text boxes contain gray text such as "enter user name"

Any ideas on how to do this?

Edit:

I ended up using the suggestion to overlay a textbox, and change its visibility based on the value of SelecteItem


回答1:


Try This- Change ItemsSource and SelectedValue according to your code.I just Showed How you can Achieve this..

<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>

or Simply->

<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}"/>


来源:https://stackoverflow.com/questions/18113293/display-select-an-item-in-combobox-when-selecteditem-is-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!