开发者

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:

--Se开发者_如何学JAVAlect 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜