简体   繁体   中英

Set Default Value For ComboBox

Tried to do some searching on this, but couldn't find exactly what I needed. I'd like to have a combobox with hardcoded items, but contain a default string. For example:

--Select Item--

Item1

Item2

Item3

I do not want the --Select Item-- to appear within the list, only on the combobox itself. Also I do not want this value to be editable.

Thanks.

You could override the default template and to include a TextBlock there which only is visible if the SelectedItem is null (use a style with datatrigger for that). To get a default tenmplate you can modify check MSDN ( Default WPF Themes link).

To do this you'll have to extened the combo box class and add this additional fundtionality. I'd start by writing a method to accept a default value, then write a new method for retrieving the list of items that excludes the default item.

You may also want to handle returning NULL when the default value is selected, as well maybe looking into adjusting the selected index of selected items to account for having an extra item in the list, for example

I think the easiest way to do this is with a simple style:

<ComboBox>
  <ComboBox.Style>
    <Style TargetType="ComboBox">
      <Setter Property="IsEditable" Value="True" />
      <Setter Property="IsReadOnly" Value="True" />

      <Style.Triggers>
        <Trigger Property="SelectedIndex" Value="-1">
          <Setter Property="Text" Value="-- Select Item --" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </ComboBox.Style>
</ComboBox>

Setting the IsEditable="True" enables the Text property on the ComboBox. In order to ensure that the Text property can not be edited, IsReadOnly="True" is also required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM