Scott Baker
Scott Baker

Reputation: 10443

Styling and Formatting the ComboBox selected item to match the ItemTemplate

I have bound a ComboBox to a list of DateTime values to select a start time for an event. I am using an ItemTemplate to specify the formatting of the DateTime in the list. I also want the user to be able to manually specify a start time not in the list, like 8:27 AM or 9:30 PM.

Wiring that up is not the issue; rather, I want the user to be presented with the same formatted DateTime as the list.

<ComboBox x:Name="StartTimeButton"
          ItemsSource="{Binding DataContext.StartTimes, 
                                RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
          SelectedItem="{Binding DefaultStartTime}"
          IsEditable="True">
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <Label>
            <TextBlock Text="{Binding StringFormat='{}{0:hh:mm tt}'}" />
         </Label>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

This results in:

Editable Text Area is not formatted the same as the dropdown area.

I have been unable to determine how to format the top TextBlock used by the ComboBox (when editing is enabled) to match the formatting of the dropdown area.

Upvotes: 3

Views: 2120

Answers (1)

brunnerh
brunnerh

Reputation: 184296

The ultra shorthand that gets you halfway there (you can drop the DataTemplate):

<ComboBox ItemsSource="{Binding Times}"
          IsEditable="True" ItemStringFormat="hh:mm tt"
          TextSearch.TextPath="Hour"/>

The problem is, that DateTime has no property that outputs the time in that format. Personally, i would write a wrapper that has an internal DateTime and a property that facilitates formatting to string and parsing from it.

There does not appear to be a standard way of creating a new item form the entered text, so you might need to parse the ComboBox.Text manually in case a value is entered that is not in the list.

Upvotes: 1

Related Questions